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 & }
@Override public ObjectNode encode(Intent intent, CodecContext context) { checkNotNull(intent, "Intent cannot be null"); final ObjectNode result = context.mapper().createObjectNode() .put(TYPE, intent.getClass().getSimpleName()) .put(ID, intent.id().toString()) .put(APP_ID, UrlEscapers.urlPathSegmentEscaper() .escape(intent.appId().name())); final ArrayNode jsonResources = result.putArray(RESOURCES); for (final NetworkResource resource : intent.resources()) { jsonResources.add(resource.toString()); } IntentService service = context.getService(IntentService.class); IntentState state = service.getIntentState(intent.key()); if (state != null) { result.put(STATE, state.toString()); } return result; }
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(); }
@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(); }
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; }
@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 ); } ); }
@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 ); } ); }
private void uiReportEntityMentionsAggregate(final Map<String, Object> model, final URI entityID) throws Throwable { // Do nothing in case the entity ID is missing if (entityID == null) { return; } // Render the table final Stream<Record> mentions = getEntityMentions(entityID, Integer.MAX_VALUE, null); final Predicate<URI> filter = Predicates.not(Predicates.in(ImmutableSet.<URI>of( NIF.BEGIN_INDEX, NIF.END_INDEX, KS.MENTION_OF))); final String linkTemplate = "ui?action=entity-mentions&entity=" + UrlEscapers.urlFormParameterEscaper().escape(entityID.stringValue()) + "&property=${property}&value=${value}"; model.put("propertyValuesTable", RenderUtils.renderRecordsAggregateTable( new StringBuilder(), mentions, filter, linkTemplate, null)); }
private void uiReportMentionValueOccurrences(final Map<String, Object> model, final URI entityID, @Nullable final URI property) throws Throwable { // Do nothing in case the entity ID is missing if (entityID == null || property == null) { return; } // Compute the # of occurrences of all the values of the given property in entity mentions final Multiset<Value> propertyValues = HashMultiset.create(); for (final Record mention : getEntityMentions(entityID, Integer.MAX_VALUE, null)) { propertyValues.addAll(mention.get(property, Value.class)); } // Render the table final Escaper esc = UrlEscapers.urlFormParameterEscaper(); final String linkTemplate = "ui?action=entity-mentions&entity=" + esc.escape(entityID.stringValue()) + "&property=" + esc.escape(Data.toString(property, Data.getNamespaceMap())) + "&value=${element}"; model.put("valueOccurrencesTable", RenderUtils.renderMultisetTable(new StringBuilder(), propertyValues, "Property value", "# Mentions", linkTemplate)); }
private void uiReportMentionPropertyOccurrences(final Map<String, Object> model, final URI entityID) throws Throwable { // Do nothing in case the entity ID is missing if (entityID == null) { return; } // Compute the # of occurrences of each property URI in entity mentions final Multiset<URI> propertyURIs = HashMultiset.create(); for (final Record mention : getEntityMentions(entityID, Integer.MAX_VALUE, null)) { propertyURIs.addAll(mention.getProperties()); } // Render the table final Escaper esc = UrlEscapers.urlFormParameterEscaper(); final String linkTemplate = "ui?action=entity-mentions&entity=" + esc.escape(entityID.stringValue()) + "&property=${element}"; model.put("propertyOccurrencesTable", RenderUtils.renderMultisetTable(new StringBuilder(), propertyURIs, "Property", "# Mentions", linkTemplate)); }
public boolean projectExists(String projectId) throws IOException { ListenableFuture<String> jsonChangeInfoHolder = HttpHelper.getAsyncFromHttp(new URL(gerritURL + "projects/" + UrlEscapers.urlPathSegmentEscaper().escape(projectId))); try { String json = jsonChangeInfoHolder.get(20000, TimeUnit.MILLISECONDS); if ("NOT FOUND".equalsIgnoreCase(json.trim())) { return false; } json = json.substring(4); JsonParser parser = new JsonParser(); JsonObject jsonObj = parser.parse(json).getAsJsonObject(); JsonElement stateElement = jsonObj.get("state"); String state = stateElement != null ? stateElement.getAsString() : null; return "ACTIVE".equals(state); } catch (Exception e) { e.printStackTrace(); } return false; }
public boolean userExists(String userId) throws IOException { ListenableFuture<String> jsonChangeInfoHolder = HttpHelper.getAsyncFromHttp(new URL(gerritURL + "accounts/" + UrlEscapers.urlPathSegmentEscaper().escape(userId))); try { String json = jsonChangeInfoHolder.get(20000, TimeUnit.MILLISECONDS); if ("NOT FOUND".equalsIgnoreCase(json.trim())) { return false; } return true; } catch (Exception e) { e.printStackTrace(); } return false; }
public StringBuilder buildRawPathString(boolean absolute, boolean slashAtEnd, String[] segments) { StringBuilder result = new StringBuilder(); if (absolute) { result.append('/'); } boolean addedOne = false; for (String s : segments) { result.append(UrlEscapers.urlPathSegmentEscaper() .escape(s)); result.append('/'); addedOne = true; } if (addedOne && !slashAtEnd) { result.deleteCharAt(result.length() - 1); } return result; }
public static CharSequence buildQueryParametersString(Multimap<String, String> currentQueryParameters) { StringBuilder paramsString = new StringBuilder(); boolean first = true; for (Map.Entry<String, String> entry : currentQueryParameters.entries()) { if (!first) { paramsString.append('&'); } String keyEnc = UrlEscapers.urlFormParameterEscaper() .escape(entry.getKey()); if (entry.getValue() != null) { String valueEnc = UrlEscapers.urlFormParameterEscaper() .escape(entry.getValue()); paramsString.append(keyEnc) .append('=') .append(valueEnc); } else { paramsString.append(keyEnc); } first = false; } return paramsString; }
@Override public String[] transform(final InputRow inputRow) { final String value = inputRow.getValue(column); if (value == null) { return new String[1]; } final Escaper escaper; switch (targetFormat) { case FORM_PARAMETER: escaper = UrlEscapers.urlFormParameterEscaper(); break; case FRAGMENT: escaper = UrlEscapers.urlFragmentEscaper(); break; case PATH_SEGMENT: escaper = UrlEscapers.urlPathSegmentEscaper(); break; default: throw new UnsupportedOperationException(); } final String escaped = escaper.escape(value); return new String[] { escaped }; }
public void exportSession(String username, String password, String issueKey, String sessionName, String jiraInstanceUrl) throws JiraExportException { sessionName = UrlEscapers.urlFragmentEscaper().escape(sessionName); try { String stream = compressedSession.get(); // client ExportResult res = client.exportSession(new ExportParams(username, password, jiraInstanceUrl, issueKey, sessionName), stream); if (res.status == ExportStatus.ERROR) { throw new JiraExportException(res.msg); } } catch (Exception e) { log.error("", e); throw new JiraExportException(e.getLocalizedMessage()); } }
private List<Ingredient> loadIngredients(final String recipeName) throws IOException { final String escapedRecipeName = UrlEscapers.urlPathSegmentEscaper().escape(recipeName); final String urlString = String.format(URL_PATTERN, escapedRecipeName); final URL url = new URL(urlString); LOGGER.d("Loading ingredients from %s", url); final HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); if (httpURLConnection.getResponseCode() != HttpURLConnection.HTTP_OK) { throw new IOException(httpURLConnection.getResponseMessage()); } final Reader reader = new InputStreamReader(httpURLConnection.getInputStream()); final TypeToken<ArrayList<Ingredient>> typeToken = new TypeToken<ArrayList<Ingredient>>() { }; return GSON.fromJson(reader, typeToken.getType()); }
public Merger expand(Map<String, Object> pathParameters) { Matcher m = PATH_VARIABLE_PATTERN.matcher(template); StringBuffer sb = new StringBuffer(); while (m.find()) { Object replacement = pathParameters.get(m.group(1)); Preconditions.checkState(null != replacement, "Unknown path variable: %s", m.group(1)); //noinspection ConstantConditions m.appendReplacement(sb, Matcher.quoteReplacement(UrlEscapers.urlPathSegmentEscaper().escape(replacement.toString()))); } m.appendTail(sb); this.template = new StringBuilder(sb); return this; }
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; }
/** * Get a signed url to view an attachment. The url will last 24 hours. The file name portion of the id is url escaped internally. * * @param id The id of the attachment. * @return Url */ public String getDownloadUrl(String id) { String filename = FilenameUtils.getName(id); String path = FilenameUtils.getFullPath(id); String escapedFullPath = FilenameUtils.concat(path, UrlEscapers.urlFragmentEscaper().escape(filename)); return cloudStorage.generateSignedUrl(gcsDefaultBucket, escapedFullPath, DEFAULT_LINK_EXPIRY_DURATION); }
/** Returns this SolrParams as a properly URL encoded string, starting with {@code "?"}, if not empty. */ public String toQueryString() { Escaper escaper = UrlEscapers.urlFragmentEscaper(); final StringBuilder sb = new StringBuilder(128); boolean first = true; for (final Iterator<String> it = getParameterNamesIterator(); it.hasNext();) { final String name = it.next(), nameEnc = escaper.escape(name); for (String val : getParams(name)) { sb.append(first ? '?' : '&').append(nameEnc).append('=').append(escaper.escape(val)); first = false; } } return sb.toString(); }
@Test public void testAssembleQueryConfigUrl() throws Exception { Gson gson = new Gson(); String someUri = "http://someServer"; String someAppId = "someAppId"; String someCluster = "someCluster+ &.-_someSign"; String someReleaseKey = "20160705193346-583078ef5716c055+20160705193308-31c471ddf9087c3f"; ApolloNotificationMessages notificationMessages = new ApolloNotificationMessages(); String someKey = "someKey"; long someNotificationId = 1; String anotherKey = "anotherKey"; long anotherNotificationId = 2; notificationMessages.put(someKey, someNotificationId); notificationMessages.put(anotherKey, anotherNotificationId); RemoteConfigRepository remoteConfigRepository = new RemoteConfigRepository(someNamespace); ApolloConfig someApolloConfig = mock(ApolloConfig.class); when(someApolloConfig.getReleaseKey()).thenReturn(someReleaseKey); String queryConfigUrl = remoteConfigRepository .assembleQueryConfigUrl(someUri, someAppId, someCluster, someNamespace, null, notificationMessages, someApolloConfig); remoteConfigLongPollService.stopLongPollingRefresh(); assertTrue(queryConfigUrl .contains( "http://someServer/configs/someAppId/someCluster+%20&.-_someSign/" + someNamespace)); assertTrue(queryConfigUrl .contains("releaseKey=20160705193346-583078ef5716c055%2B20160705193308-31c471ddf9087c3f")); assertTrue(queryConfigUrl .contains("messages=" + UrlEscapers.urlFormParameterEscaper().escape(gson.toJson(notificationMessages)))); }
private Archive(Archive container, String fileName) { while (container != null && !fileName.startsWith(container.fileName)) { container = container.container; } this.container = container; this.fileName = fileName; this.nestedPath = new StringBuilder() .append(LegacyUtilities.guessScheme(fileName)).append(':') .append(UrlEscapers.urlPathSegmentEscaper().escape(computePath(container, fileName))).append('#') .toString(); }
public static String computePath(Archive container, String fileName) { if (container != null) { int endIndex = fileName.endsWith("/") ? fileName.length() - 1 : fileName.length(); String path = fileName.substring(container.fileName.length(), endIndex); return container.nestedPath + UrlEscapers.urlFragmentEscaper().escape(path); } else { checkArgument(fileName.startsWith("./"), "invalid BDIO 1.x fileName (must start with './'): %s", fileName); return "file:///" + Joiner.on('/').join(Iterables.transform( Splitter.on('/').omitEmptyStrings().split(fileName.substring(2)), UrlEscapers.urlPathSegmentEscaper().asFunction())); } }
@Override public void selectionChanged(SelectionChangedEvent event) { projectSelector.clearStatusLink(); latestQueryJob = null; IStructuredSelection selection = (IStructuredSelection) event.getSelection(); if (selection.isEmpty()) { return; } GcpProject project = (GcpProject) selection.getFirstElement(); String email = accountSelector.getSelectedEmail(); String createAppLink = MessageFormat.format(CREATE_APP_LINK, project.getId(), UrlEscapers.urlFormParameterEscaper().escape(email)); boolean queryCached = project.hasAppEngineInfo(); if (queryCached) { if (project.getAppEngine() == AppEngine.NO_APPENGINE_APPLICATION) { projectSelector.setStatusLink( Messages.getString("projectselector.missing.appengine.application.link", createAppLink), createAppLink /* tooltip */); } } else { // The project has never been queried. Credential credential = accountSelector.getSelectedCredential(); latestQueryJob = new AppEngineApplicationQueryJob(project, credential, projectRepository, projectSelector, createAppLink, isLatestQueryJob); latestQueryJob.schedule(); } }
@VisibleForTesting static String formatReportUrl() { String body = MessageFormat.format(BODY_TEMPLATE, CloudToolsInfo.getToolsVersion(), getCloudSdkVersion(), getEclipseVersion(), System.getProperty("os.name"), System.getProperty("os.version"), System.getProperty("java.version")); Escaper escaper = UrlEscapers.urlFormParameterEscaper(); return BUG_REPORT_URL + "?body=" + escaper.escape(body); }
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()); }
/** * Encode the URL fragment. This method will also encode '?' and '/' characters in the provided fragment. * * @param fragment * @return */ public static String encodeFragment(String fragment) { String partiallyEncodedFragment = UrlEscapers.urlFragmentEscaper().escape(fragment); partiallyEncodedFragment = partiallyEncodedFragment.replaceAll("\\?", "%3F"); partiallyEncodedFragment = partiallyEncodedFragment.replaceAll("/", "%2F"); return partiallyEncodedFragment; }
public String paste() { try { HttpURLConnection httpConnection = (HttpURLConnection) new URL(PASTE_URL).openConnection(); httpConnection.setRequestMethod("POST"); httpConnection.setDoOutput(true); httpConnection.setDoInput(true); try (BufferedWriter writer = new BufferedWriter( new OutputStreamWriter(httpConnection.getOutputStream(), StandardCharsets.UTF_8)) ) { writer.write("content=" + UrlEscapers.urlPathSegmentEscaper().escape(toString())); writer.write("&from=" + plugin.getName()); } JsonObject object; try (Reader reader = new BufferedReader( new InputStreamReader(httpConnection.getInputStream(), StandardCharsets.UTF_8)) ) { object = new Gson().fromJson(reader, JsonObject.class); } if (object.has("url")) { return object.get("url").getAsString(); } plugin.getLogger().info("Failed to parse url"); } catch (IOException ex) { plugin.getLogger().log(Level.SEVERE, null, ex); } return null; }
@Override protected void doRequest(final HttpClient client) { // Build query URI Escaper escaper = UrlEscapers.urlFormParameterEscaper(); StringBuilder queryUri = new StringBuilder(INFLUXDB_QUERY_URI); queryUri.append(escaper.escape(m_query)); m_logger.debug("Executing query: {} (host: {})", queryUri, getConnection().getAddress()); HttpClientRequest request = doGet(queryUri.toString(), new HttpClientResponseAdapter() { @Override protected void handleFailure(final HttpClientResponse response) { if (response.statusCode() != 200) { m_logger.error("Failed to execute query: {} (host: {})", m_query, getConnection().getAddress(), new IllegalStateException("HTTP get failure: " + response.statusCode() + "/" + response.statusMessage())); } } }); // HTTP basic authentication if (!Strings.isNullOrEmpty(m_adminUser)) { request.putHeader(HttpHeaders.Names.AUTHORIZATION, "Basic " + base64UserAndPassword(m_adminUser, m_adminPassword)); } request.exceptionHandler(new DefaultConnectionExceptionHandler( getConnection())); request.end(); }
@RequestMapping ( value = "/channel/{channelId}/artifact/{artifactId}/attach", method = RequestMethod.POST ) public ModelAndView attachArtifactPost ( @PathVariable ( "channelId" ) final String channelId, @PathVariable ( "artifactId" ) final String artifactId, @RequestParameter ( required = false, value = "name" ) final String name, final @RequestParameter ( "file" ) Part file ) { return withChannel ( channelId, ModifiableChannel.class, channel -> { String targetName = name; final Optional<ChannelArtifactInformation> parentArtifact = channel.getArtifact ( artifactId ); if ( !parentArtifact.isPresent () ) { return CommonController.createNotFound ( "artifact", artifactId ); } try { if ( targetName == null || targetName.isEmpty () ) { targetName = file.getSubmittedFileName (); } channel.getContext ().createArtifact ( artifactId, file.getInputStream (), targetName, null ); } catch ( final IOException e ) { return new ModelAndView ( "/error/upload" ); } return new ModelAndView ( "redirect:/channel/" + UrlEscapers.urlPathSegmentEscaper ().escape ( channelId ) + "/view" ); } ); }
@RequestMapping ( value = "/channel/{channelId}/artifacts/{artifactId}/generate", method = RequestMethod.GET ) @HttpConstraint ( PERMIT ) public ModelAndView generate ( @PathVariable ( "channelId" ) final String channelId, @PathVariable ( "artifactId" ) final String artifactId) { return Channels.withArtifact ( this.service, channelId, artifactId, ModifiableChannel.class, ( channel, artifact ) -> { channel.getContext ().regenerate ( artifact.getId () ); return new ModelAndView ( "redirect:/channel/" + UrlEscapers.urlPathSegmentEscaper ().escape ( artifact.getChannelId ().getId () ) + "/view" ); } ); }
private void fillModel ( final Map<String, Object> model, final String channelId ) { final List<Entry> entries = new LinkedList<> (); entries.add ( new Entry ( "Home", "/" ) ); entries.add ( new Entry ( "Channel", "/channel/" + UrlEscapers.urlPathSegmentEscaper ().escape ( channelId ) + "/view" ) ); entries.add ( new Entry ( "Cleanup" ) ); model.put ( "breadcrumbs", new Breadcrumbs ( entries ) ); }
public LinkTarget expandSource ( final ReplaceSource source ) { if ( this.url == null || source == null ) { return this; } final ReplaceSource encodeSource = new EscaperSource ( source, UrlEscapers.urlPathSegmentEscaper () ); return new LinkTarget ( StringReplacer.replace ( this.url, encodeSource, PATTERN, false ) ); }
@Test public void testEncode() throws UnsupportedEncodingException { assertThat( UrlEscapers.urlFragmentEscaper().escape("Test Title"), equalTo("Test%20Title") ); assertThat( Redirect.success() .title("Test Title") .msg("Test Message") .toString(), equalTo("http://s.wts.sola.love/nm/v2/result.html?type=1&title=Test%20Title&msg=Test%20Message&") ); }