com.google.common.net.UrlEscapers Java Examples

The following examples show how to use com.google.common.net.UrlEscapers. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: HttpRequest.java    From timbuctoo with GNU General Public License v3.0 6 votes vote down vote up
public String getPathAndQuery() {

    String url = this.path;
    boolean isFirst = true;
    for (Map.Entry<String, String> queryParameter : this.queryParameters.entries()) {
      if (isFirst) {
        url += "?";
        isFirst = false;
      } else {
        url += "&";
      }
      Escaper escaper = UrlEscapers.urlFormParameterEscaper();
      url += escaper.escape(queryParameter.getKey()) + "=" + escaper.escape(queryParameter.getValue());
    }

    return url;
  }
 
Example #2
Source File: Breadcrumbs.java    From packagedrone with Eclipse Public License 1.0 6 votes vote down vote up
public Builder add ( final String label, final String targetPattern, final String... pathSegments )
{
    Objects.requireNonNull ( targetPattern );
    Objects.requireNonNull ( pathSegments );

    final Escaper esc = UrlEscapers.urlPathSegmentEscaper ();

    final Object[] encoded = new String[pathSegments.length];
    for ( int i = 0; i < pathSegments.length; i++ )
    {
        encoded[i] = esc.escape ( pathSegments[i] );
    }

    this.entries.add ( new Entry ( label, MessageFormat.format ( targetPattern, encoded ) ) );
    return this;
}
 
Example #3
Source File: UrlUtils.java    From short-url with Apache License 2.0 6 votes vote down vote up
public static String encodePath(String path) {
	if (path.isEmpty() || path.equals("/")) {
		return path;
	}
	
	StringBuilder sb = new StringBuilder();
	Escaper escaper = UrlEscapers.urlPathSegmentEscaper();
	Iterable<String> iterable = pathSplitter.split(path);
	Iterator<String> iterator = iterable.iterator();
	while (iterator.hasNext()) {
		String part = iterator.next();
		if (part.isEmpty()) {
			sb.append("/");
			continue;
		}
		
		part = escaper.escape(part);
		sb.append(part);
		if (iterator.hasNext()) {
			sb.append("/");
		}
	}
	
	return sb.toString();
}
 
Example #4
Source File: BinanceHistoryFilter.java    From java-binance-api with MIT License 6 votes vote down vote up
public String getAsQuery() {
    StringBuffer sb = new StringBuffer();
    Escaper esc = UrlEscapers.urlFormParameterEscaper();

    if (!Strings.isNullOrEmpty(asset)) {
        sb.append("&asset=").append(esc.escape(asset));
    }
    if (startTime != null) {
        sb.append("&startTime=").append(startTime.getTime());
    }
    if (endTime != null) {
        sb.append("&endTime=").append(endTime.getTime());
    }
    String s = sb.toString();
    return s.length() > 1 ? s.substring(1) : s; // skipping the first &
}
 
Example #5
Source File: P2MetaDataController.java    From packagedrone with Eclipse Public License 1.0 6 votes vote down vote up
@RequestMapping ( value = "/{channelId}/edit", method = RequestMethod.POST )
public ModelAndView editPost ( @PathVariable ( "channelId" ) final String channelId, @Valid @FormData ( "command" ) final P2MetaDataInformation data, final BindingResult result) throws Exception
{
    return Channels.withChannel ( this.service, channelId, ModifiableChannel.class, channel -> {

        final Map<String, Object> model = new HashMap<> ();

        if ( result.hasErrors () )
        {
            model.put ( "channel", channel.getInformation () );
            model.put ( "command", data );
            fillBreadcrumbs ( model, channelId, "Edit" );
            return new ModelAndView ( "p2edit", model );
        }

        final Map<MetaKey, String> providedMetaData = MetaKeys.unbind ( data );

        channel.applyMetaData ( providedMetaData );

        return new ModelAndView ( "redirect:/p2.metadata/" + UrlEscapers.urlPathSegmentEscaper ().escape ( channelId ) + "/info", model );
    } );
}
 
Example #6
Source File: P2RepoController.java    From packagedrone with Eclipse Public License 1.0 6 votes vote down vote up
@RequestMapping ( value = "/{channelId}/edit", method = RequestMethod.POST )
public ModelAndView editPost ( @PathVariable ( "channelId" ) final String channelId, @Valid @FormData ( "command" ) final P2ChannelInformation data, final BindingResult result) throws Exception
{
    return Channels.withChannel ( this.service, channelId, ModifiableChannel.class, channel -> {

        final Map<String, Object> model = new HashMap<> ();

        if ( result.hasErrors () )
        {
            model.put ( "channel", channel.getInformation () );
            model.put ( "command", data );
            fillBreadcrumbs ( model, channelId, "Edit" );
            return new ModelAndView ( "p2edit", model );
        }

        final Map<MetaKey, String> providedMetaData = MetaKeys.unbind ( data );

        channel.applyMetaData ( providedMetaData );

        return new ModelAndView ( "redirect:/p2.repo/" + UrlEscapers.urlPathSegmentEscaper ().escape ( channelId ) + "/info", model );
    } );
}
 
Example #7
Source File: DaxTrackerServerApi.java    From Runescape-Web-Walker-Engine with Apache License 2.0 6 votes vote down vote up
public PropertyStats getStats(String user, String source, String propertyName) {
    ServerResponse serverResponse;
    Escaper escaper = UrlEscapers.urlFormParameterEscaper();
    try {
        serverResponse = IOHelper.get(
                TRACKER_ENDPOINT + "/tracker/data?user=" + escaper.escape(user)
                        + "&propertyName=" + escaper.escape(propertyName)
                        + (source != null ? "&source=" + escaper.escape(source) : ""),
                daxCredentialsProvider
        );
    } catch (IOException e) {
        return null;
    }

    if (serverResponse.getCode() != HttpURLConnection.HTTP_OK) {
        log("ERROR: " + new JsonParser().parse(serverResponse.getContents()).getAsJsonObject().get("message").getAsString());
        return null;
    }

    return new Gson().fromJson(serverResponse.getContents(), PropertyStats.class);
}
 
Example #8
Source File: DaxTrackerServerApi.java    From Runescape-Web-Walker-Engine with Apache License 2.0 6 votes vote down vote up
public UserHighScore topUsers(String propertyName, Period period) {
    ServerResponse serverResponse;
    Escaper escaper = UrlEscapers.urlFormParameterEscaper();
    try {
        serverResponse = IOHelper.get(
                TRACKER_ENDPOINT + "/tracker/users/top?propertyName=" + escaper.escape(propertyName)
                        + (period != null ? "&period=" + period : ""),
                daxCredentialsProvider
        );
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }

    if (serverResponse.getCode() != HttpURLConnection.HTTP_OK) {
        log("ERROR: " + new JsonParser().parse(serverResponse.getContents()).getAsJsonObject().get("message").getAsString());
        return null;
    }

    return new Gson().fromJson(serverResponse.getContents(), UserHighScore.class);
}
 
Example #9
Source File: DaxTrackerServerApi.java    From Runescape-Web-Walker-Engine with Apache License 2.0 6 votes vote down vote up
public SourceHighScore topSources(String user, String propertyName, Period period) {
    ServerResponse serverResponse;
    Escaper escaper = UrlEscapers.urlFormParameterEscaper();
    try {
        serverResponse = IOHelper.get(
                TRACKER_ENDPOINT + "/tracker/sources/top?propertyName=" + escaper.escape(propertyName)
                        + "&user=" + user
                        + (period != null ? "&period=" + period : ""),
                daxCredentialsProvider
        );
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }

    if (serverResponse.getCode() != HttpURLConnection.HTTP_OK) {
        log("ERROR: " + new JsonParser().parse(serverResponse.getContents()).getAsJsonObject().get("message").getAsString());
        return null;
    }

    return new Gson().fromJson(serverResponse.getContents(), SourceHighScore.class);
}
 
Example #10
Source File: DaxTrackerServerApi.java    From Runescape-Web-Walker-Engine with Apache License 2.0 6 votes vote down vote up
public ListSearch usersOnline(String propertyName, Period period) {
    ServerResponse serverResponse;
    Escaper escaper = UrlEscapers.urlFormParameterEscaper();
    try {
        serverResponse = IOHelper.get(
                TRACKER_ENDPOINT + "/tracker/users/online?"
                        + (propertyName != null ? "&propertyName=" + escaper.escape(propertyName) : "")
                        + (period != null ? "&period=" + period : ""),
                daxCredentialsProvider
        );
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }

    if (serverResponse.getCode() != HttpURLConnection.HTTP_OK) {
        log("ERROR: " + new JsonParser().parse(serverResponse.getContents()).getAsJsonObject().get("message").getAsString());
        return null;
    }

    return new Gson().fromJson(serverResponse.getContents(), ListSearch.class);
}
 
Example #11
Source File: DaxTrackerServerApi.java    From Runescape-Web-Walker-Engine with Apache License 2.0 6 votes vote down vote up
public ListSearch sourcesOnline(String propertyName, String user, Period period) {
    ServerResponse serverResponse;
    Escaper escaper = UrlEscapers.urlFormParameterEscaper();
    try {
        serverResponse = IOHelper.get(
                TRACKER_ENDPOINT + "/tracker/sources/online?propertyName=" + escaper.escape(propertyName)
                        + "&user=" + escaper.escape(user)
                        + (period != null ? "&period=" + period : ""),
                daxCredentialsProvider
        );
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }

    if (serverResponse.getCode() != HttpURLConnection.HTTP_OK) {
        log("ERROR: " + new JsonParser().parse(serverResponse.getContents()).getAsJsonObject().get("message").getAsString());
        return null;
    }

    return new Gson().fromJson(serverResponse.getContents(), ListSearch.class);
}
 
Example #12
Source File: DefaultDockerCmdExecFactory.java    From docker-java with Apache License 2.0 6 votes vote down vote up
@Override
public InvocationBuilder request() {
    String resource = StringUtils.join(path, "/");

    if (!resource.startsWith("/")) {
        resource = "/" + resource;
    }

    if (!queryParams.isEmpty()) {
        Escaper urlFormParameterEscaper = UrlEscapers.urlFormParameterEscaper();
        resource = queryParams.asMap().entrySet().stream()
            .flatMap(entry -> {
                return entry.getValue().stream().map(s -> {
                    return entry.getKey() + "=" + urlFormParameterEscaper.escape(s);
                });
            })
            .collect(Collectors.joining("&", resource + "?", ""));
    }

    return new DefaultInvocationBuilder(
        dockerHttpClient, objectMapper, resource
    );
}
 
Example #13
Source File: HttpRequest.java    From timbuctoo with GNU General Public License v3.0 6 votes vote down vote up
public String getPathAndQuery() {
  String url = this.path;
  boolean isFirst = true;
  for (Map.Entry<String, String> queryParameter : this.queryParameters.entries()) {
    if (isFirst) {
      url += "?";
      isFirst = false;
    } else {
      url += "&";
    }
    Escaper escaper = UrlEscapers.urlFormParameterEscaper();
    url += escaper.escape(queryParameter.getKey()) + "=" + escaper.escape(queryParameter.getValue());
  }

  return url;
}
 
Example #14
Source File: ITPutAzureDataLakeStorage.java    From nifi with Apache License 2.0 6 votes vote down vote up
private void assertFlowFile(byte[] fileData, String fileName, String directory) throws Exception {
    MockFlowFile flowFile = assertFlowFile(fileData);

    flowFile.assertAttributeEquals("azure.filesystem", fileSystemName);
    flowFile.assertAttributeEquals("azure.directory", directory);
    flowFile.assertAttributeEquals("azure.filename", fileName);

    String urlEscapedDirectory = UrlEscapers.urlPathSegmentEscaper().escape(directory);
    String urlEscapedFileName = UrlEscapers.urlPathSegmentEscaper().escape(fileName);
    String primaryUri = StringUtils.isNotEmpty(directory)
            ? String.format("https://%s.dfs.core.windows.net/%s/%s/%s", getAccountName(), fileSystemName, urlEscapedDirectory, urlEscapedFileName)
            : String.format("https://%s.dfs.core.windows.net/%s/%s", getAccountName(), fileSystemName, urlEscapedFileName);
    flowFile.assertAttributeEquals("azure.primaryUri", primaryUri);

    flowFile.assertAttributeEquals("azure.length", Integer.toString(fileData.length));
}
 
Example #15
Source File: RequestForwardUtils.java    From tds with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public static void forwardRequestRelativeToCurrentContext(String fwdPath, HttpServletRequest request,
    HttpServletResponse response) throws IOException, ServletException {

  if (fwdPath == null || request == null || response == null) {
    String msg = "Path, request, and response may not be null";
    log.error(
        "forwardRequestRelativeToCurrentContext() ERROR: " + msg + (fwdPath == null ? ": " : "[" + fwdPath + "]: "));
    throw new IllegalArgumentException(msg + ".");
  }

  Escaper urlPathEscaper = UrlEscapers.urlPathSegmentEscaper();

  String encodedPath = urlPathEscaper.escape(fwdPath); // LOOK path vs query
  RequestDispatcher dispatcher = request.getRequestDispatcher(encodedPath);

  if (dispatcherWasFound(encodedPath, dispatcher, response))
    dispatcher.forward(request, response);
}
 
Example #16
Source File: RequestForwardUtils.java    From tds with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public static void forwardRequestRelativeToGivenContext(String fwdPath, ServletContext targetContext,
    HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
  if (fwdPath == null || targetContext == null || request == null || response == null) {
    String msg = "Path, context, request, and response may not be null";
    log.error(
        "forwardRequestRelativeToGivenContext() ERROR: " + msg + (fwdPath == null ? ": " : "[" + fwdPath + "]: "));
    throw new IllegalArgumentException(msg + ".");
  }

  Escaper urlPathEscaper = UrlEscapers.urlPathSegmentEscaper();
  String encodedPath = urlPathEscaper.escape(fwdPath); // LOOK path vs query
  RequestDispatcher dispatcher = targetContext.getRequestDispatcher(encodedPath);

  if (dispatcherWasFound(encodedPath, dispatcher, response))
    dispatcher.forward(request, response);
}
 
Example #17
Source File: Utils.java    From rmlmapper-java with MIT License 6 votes vote down vote up
public static String encodeURI(String url) {
    Escaper escaper = UrlEscapers.urlFragmentEscaper();
    String result = escaper.escape(url);

    result = result.replaceAll("!", "%21");
    result = result.replaceAll("#", "%23");
    result = result.replaceAll("\\$", "%24");
    result = result.replaceAll("&", "%26");
    result = result.replaceAll("'", "%27");
    result = result.replaceAll("\\(", "%28");
    result = result.replaceAll("\\)", "%29");
    result = result.replaceAll("\\*", "%2A");
    result = result.replaceAll("\\+", "%2B");
    result = result.replaceAll(",", "%2C");
    result = result.replaceAll("/", "%2F");
    result = result.replaceAll(":", "%3A");
    result = result.replaceAll(";", "%3B");
    result = result.replaceAll("=", "%3D");
    result = result.replaceAll("\\?", "%3F");
    result = result.replaceAll("@", "%40");
    result = result.replaceAll("\\[", "%5B");
    result = result.replaceAll("]", "%5D");

    return result;
}
 
Example #18
Source File: HttpUtil.java    From google-cloud-eclipse with Apache License 2.0 6 votes vote down vote up
@VisibleForTesting
static String getParametersString(Map<String, String> parametersMap) {
  StringBuilder resultBuilder = new StringBuilder();
  boolean ampersandNeeded = false;
  for (Map.Entry<String, String> entry : parametersMap.entrySet()) {
    if (ampersandNeeded) {
      resultBuilder.append('&');
    } else {
      ampersandNeeded = true;
    }
    resultBuilder.append(entry.getKey());
    resultBuilder.append('=');
    resultBuilder.append(UrlEscapers.urlFormParameterEscaper().escape(entry.getValue()));
  }
  return resultBuilder.toString();
}
 
Example #19
Source File: MojangAuthApi.java    From ChangeSkin with MIT License 6 votes vote down vote up
public void changeSkin(UUID ownerId, String accessToken, String sourceUrl, boolean slimModel) {
    String url = CHANGE_SKIN_URL.replace("<uuid>", UUIDTypeAdapter.toMojangId(ownerId));

    try {
        HttpURLConnection httpConnection = CommonUtil.getConnection(url);
        httpConnection.setRequestMethod("POST");
        httpConnection.setDoOutput(true);

        httpConnection.addRequestProperty("Authorization", "Bearer " + accessToken);
        try (BufferedWriter writer = new BufferedWriter(
                new OutputStreamWriter(httpConnection.getOutputStream(), StandardCharsets.UTF_8))) {
            writer.write("model=");
            if (slimModel) {
                writer.write("slim");
            }

            writer.write("&url=" + UrlEscapers.urlPathSegmentEscaper().escape(sourceUrl));
        }

        logger.debug("Response code for uploading {}", httpConnection.getResponseCode());
    } catch (IOException ioEx) {
        logger.error("Tried uploading {}'s skin data {} to Mojang {}", ownerId, sourceUrl, url, ioEx);
    }
}
 
Example #20
Source File: DeviceRegistryHttpClient.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
private static String credentialsInstanceUri(final String tenant, final String authId, final String type) {
    return String.format(
            TEMPLATE_URI_CREDENTIALS_INSTANCE,
            Optional.ofNullable(tenant)
                .map(t -> UrlEscapers.urlPathSegmentEscaper().escape(t))
                .orElse(""),
            Optional.ofNullable(authId)
                .map(a -> UrlEscapers.urlPathSegmentEscaper().escape(a))
                .orElse(""),
            Optional.ofNullable(type)
                .map(t -> UrlEscapers.urlPathSegmentEscaper().escape(t))
                .orElse(""));
}
 
Example #21
Source File: DeviceRegistryHttpClient.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
private static String tenantInstanceUri(final String tenant) {
    return String.format(
            TEMPLATE_URI_TENANT_INSTANCE,
            Optional.ofNullable(tenant)
                .map(t -> UrlEscapers.urlPathSegmentEscaper().escape(t))
                .orElse(""));
}
 
Example #22
Source File: DeviceRegistryHttpClient.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
private static String registrationInstanceUri(final String tenant, final String deviceId) {
    return String.format(
            TEMPLATE_URI_REGISTRATION_INSTANCE,
            Optional.ofNullable(tenant)
                .map(t -> UrlEscapers.urlPathSegmentEscaper().escape(t))
                .orElse(""),
            Optional.ofNullable(deviceId)
                .map(d -> UrlEscapers.urlPathSegmentEscaper().escape(d))
                .orElse(""));
}
 
Example #23
Source File: DeviceRegistryHttpClient.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
private static String registrationWithoutIdUri(final String tenant) {
    return String.format(
            TEMPLATE_URI_REGISTRATION_WITHOUT_ID,
            Optional.ofNullable(tenant)
                .map(t -> UrlEscapers.urlPathSegmentEscaper().escape(t))
                .orElse(""));
}
 
Example #24
Source File: DeviceRegistryHttpClient.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
private static String credentialsByDeviceUri(final String tenant, final String deviceId) {
    return String.format(
            TEMPLATE_URI_CREDENTIALS_BY_DEVICE,
            Optional.ofNullable(tenant)
                .map(t -> UrlEscapers.urlPathSegmentEscaper().escape(t))
                .orElse(""),
            Optional.ofNullable(deviceId)
                .map(d -> UrlEscapers.urlPathSegmentEscaper().escape(d))
                .orElse(""));
}
 
Example #25
Source File: DefinitionTextUtils.java    From vscode-as3mxml with Apache License 2.0 5 votes vote down vote up
public Location toLocation()
{
    Location location = new Location();
    String escapedText = UrlEscapers.urlFragmentEscaper().escape(text);
    URI uri = URI.create("swc://" + path + "?" + escapedText);
    location.setUri(uri.toString());
    location.setRange(toRange());
    return location;
}
 
Example #26
Source File: DiskCache.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Make the cache filename
 *
 * @param fileLocation normal file location
 * @return cache filename
 */
private static String makeCachePath(String fileLocation) {
  Escaper urlPathEscaper = UrlEscapers.urlPathSegmentEscaper();

  fileLocation = fileLocation.replace('\\', '/'); // LOOK - use better normalization code eg Spring StringUtils
  String cachePath = urlPathEscaper.escape(fileLocation);

  // We need to escape ":" on windows or else our cache file will be something
  // like root + http, or root + C. We're already using UrlEscapers, so let's
  // replace ":" with "%3A"
  cachePath = cachePath.replace(":", "%3A");

  return root + cachePath;
}
 
Example #27
Source File: TargetingQueryFileConverter.java    From vespa with Apache License 2.0 5 votes vote down vote up
private static String toYqlString(Query query)  {
    StringBuilder yqlBuilder = new StringBuilder("select * from sources * where predicate(boolean, ");
    yqlBuilder
            .append(createYqlFormatSubqueryMapString(query.valuesForSubqueries, query.isSingleQuery))
            .append(", ")
            .append(createYqlFormatSubqueryMapString(query.rangesForSubqueries, query.isSingleQuery))
            .append(");");
    return "/search/?query&nocache&yql=" + UrlEscapers.urlFormParameterEscaper().escape(yqlBuilder.toString());
}
 
Example #28
Source File: ObjectStoreFileSystem.java    From stocator with Apache License 2.0 5 votes vote down vote up
@Override
public void initialize(URI fsuri, Configuration conf) throws IOException {
  super.initialize(fsuri, conf);
  LOG.trace("Initialize for {}", fsuri);
  if (!conf.getBoolean("mapreduce.fileoutputcommitter.marksuccessfuljobs", true)) {
    throw new IOException("mapreduce.fileoutputcommitter.marksuccessfuljobs should be enabled");
  }
  final String escapedAuthority = UrlEscapers
          .urlPathSegmentEscaper()
          .escape(fsuri.getAuthority());
  uri = URI.create(fsuri.getScheme() + "://" + escapedAuthority);
  setConf(conf);
  String committerType = conf.get(OUTPUT_COMMITTER_TYPE, DEFAULT_FOUTPUTCOMMITTER_V1);
  bracketGlobSupport = conf.getBoolean(FS_STOCATOR_GLOB_BRACKET_SUPPORT,
      FS_STOCATOR_GLOB_BRACKET_SUPPORT_DEFAULT.equals("true"));
  if (storageClient == null) {
    storageClient = ObjectStoreVisitor.getStoreClient(fsuri, conf);
    if (Utils.validSchema(fsuri.toString())) {
      hostNameScheme = storageClient.getScheme() + "://"  + Utils.getHost(fsuri) + "/";
    } else {
      LOG.debug("Non valid schema for {}", fsuri.toString());
      String accessURL = Utils.extractAccessURL(fsuri.toString(), storageClient.getScheme());
      LOG.debug("Non valid schema. Access url {}", accessURL);
      String dataRoot = Utils.extractDataRoot(fsuri.toString(),
          accessURL);
      if (dataRoot.isEmpty()) {
        hostNameScheme = accessURL + "/";
      } else {
        hostNameScheme = accessURL + "/" + dataRoot + "/";
      }
    }
    stocatorPath = new StocatorPath(committerType, conf, hostNameScheme);
    storageClient.setStocatorPath(stocatorPath);
    storageClient.setStatistics(statistics);
  }
}
 
Example #29
Source File: DefaultDockerCmdExecFactory.java    From docker-java with Apache License 2.0 5 votes vote down vote up
@Override
public DefaultWebTarget resolveTemplate(String name, Object value) {
    ImmutableList.Builder<String> newPath = ImmutableList.builder();
    for (String component : path) {
        component = component.replaceAll(
            "\\{" + name + "\\}",
            UrlEscapers.urlPathSegmentEscaper().escape(value.toString())
        );
        newPath.add(component);
    }

    return new DefaultWebTarget(newPath.build(), queryParams);
}
 
Example #30
Source File: AutoIndex.java    From armeria with Apache License 2.0 5 votes vote down vote up
static HttpData listingToHtml(String dirPath, String mappedDirPath, List<String> listing) {
    final Escaper htmlEscaper = HtmlEscapers.htmlEscaper();
    final Escaper urlEscaper = UrlEscapers.urlFragmentEscaper();
    final String escapedDirPath = htmlEscaper.escape(dirPath);
    final StringBuilder buf = new StringBuilder(listing.size() * 64);
    buf.append(PART1);
    buf.append(escapedDirPath);
    buf.append(PART2);
    buf.append(escapedDirPath);
    buf.append(PART3);
    buf.append(listing.size());
    buf.append(PART4);
    if (!"/".equals(mappedDirPath)) {
        buf.append("<li class=\"directory parent\"><a href=\"../\">../</a></li>\n");
    }
    for (String name : listing) {
        buf.append("<li class=\"");
        if (name.charAt(name.length() - 1) == '/') {
            buf.append("directory");
        } else {
            buf.append("file");
        }
        buf.append("\"><a href=\"");
        buf.append(urlEscaper.escape(name));
        buf.append("\">");
        buf.append(name);
        buf.append("</a></li>\n");
    }
    buf.append(PART5);
    return HttpData.ofUtf8(buf.toString());
}