I'd like to append key-value pair as a query parameter to an existing URL. While I could do this by checking for the existence of whether the URL has a query part or a fragment part and doing the append by jumping though a bunch of if-clauses but I was wondering if there was clean way if doing this through the Apache Commons libraries or something equivalent.
http://example.com would be http://example.com?name=John
http://example.com#fragment would be http://example.com?name=John#fragment
http://example.com?email=john.doe#email.com would be http://example.com?email=john.doe#email.com&name=John
http://example.com?email=john.doe#email.com#fragment would be http://example.com?email=john.doe#email.com&name=John#fragment
I've run this scenario many times before and I'd like to do this without breaking the URL in any way.
There are plenty of libraries that can help you with URI building (don't reinvent the wheel). Here are three to get you started:
Java EE 7
import javax.ws.rs.core.UriBuilder;
...
return UriBuilder.fromUri(url).queryParam(key, value).build();
org.apache.httpcomponents:httpclient:4.5.2
import org.apache.http.client.utils.URIBuilder;
...
return new URIBuilder(url).addParameter(key, value).build();
org.springframework:spring-web:4.2.5.RELEASE
import org.springframework.web.util.UriComponentsBuilder;
...
return UriComponentsBuilder.fromUriString(url).queryParam(key, value).build().toUri();
See also: GIST > URI Builder Tests
This can be done by using the java.net.URI class to construct a new instance using the parts from an existing one, this should ensure it conforms to URI syntax.
The query part will either be null or an existing string, so you can decide to append another parameter with & or start a new query.
public class StackOverflow26177749 {
public static URI appendUri(String uri, String appendQuery) throws URISyntaxException {
URI oldUri = new URI(uri);
String newQuery = oldUri.getQuery();
if (newQuery == null) {
newQuery = appendQuery;
} else {
newQuery += "&" + appendQuery;
}
return new URI(oldUri.getScheme(), oldUri.getAuthority(),
oldUri.getPath(), newQuery, oldUri.getFragment());
}
public static void main(String[] args) throws Exception {
System.out.println(appendUri("http://example.com", "name=John"));
System.out.println(appendUri("http://example.com#fragment", "name=John"));
System.out.println(appendUri("http://example.com?email=john.doe#email.com", "name=John"));
System.out.println(appendUri("http://example.com?email=john.doe#email.com#fragment", "name=John"));
}
}
Shorter alternative
public static URI appendUri(String uri, String appendQuery) throws URISyntaxException {
URI oldUri = new URI(uri);
return new URI(oldUri.getScheme(), oldUri.getAuthority(), oldUri.getPath(),
oldUri.getQuery() == null ? appendQuery : oldUri.getQuery() + "&" + appendQuery, oldUri.getFragment());
}
Output
http://example.com?name=John
http://example.com?name=John#fragment
http://example.com?email=john.doe#email.com&name=John
http://example.com?email=john.doe#email.com&name=John#fragment
For android, Use:
https://developer.android.com/reference/android/net/Uri#buildUpon()
URI oldUri = new URI(uri);
Uri.Builder builder = oldUri.buildUpon();
builder.appendQueryParameter("newParameter", "dummyvalue");
Uri newUri = builder.build();
Use the URI class.
Create a new URI with your existing String to "break it up" to parts, and instantiate another one to assemble the modified url:
URI u = new URI("http://example.com?email=john#email.com&name=John#fragment");
// Modify the query: append your new parameter
StringBuilder sb = new StringBuilder(u.getQuery() == null ? "" : u.getQuery());
if (sb.length() > 0)
sb.append('&');
sb.append(URLEncoder.encode("paramName", "UTF-8"));
sb.append('=');
sb.append(URLEncoder.encode("paramValue", "UTF-8"));
// Build the new url with the modified query:
URI u2 = new URI(u.getScheme(), u.getAuthority(), u.getPath(),
sb.toString(), u.getFragment());
I suggest an improvement of the Adam's answer accepting HashMap as parameter
/**
* Append parameters to given url
* #param url
* #param parameters
* #return new String url with given parameters
* #throws URISyntaxException
*/
public static String appendToUrl(String url, HashMap<String, String> parameters) throws URISyntaxException
{
URI uri = new URI(url);
String query = uri.getQuery();
StringBuilder builder = new StringBuilder();
if (query != null)
builder.append(query);
for (Map.Entry<String, String> entry: parameters.entrySet())
{
String keyValueParam = entry.getKey() + "=" + entry.getValue();
if (!builder.toString().isEmpty())
builder.append("&");
builder.append(keyValueParam);
}
URI newUri = new URI(uri.getScheme(), uri.getAuthority(), uri.getPath(), builder.toString(), uri.getFragment());
return newUri.toString();
}
Use this function to append a new parameter to your existing URI
private Uri appendUriParameter(Uri uri, String key, String newValue) {
final Set<String> params = uri.getQueryParameterNames();
final Uri.Builder newUri = uri.buildUpon().clearQuery();
for (String param : params) {
newUri.appendQueryParameter(param, uri.getQueryParameter(param));
}
newUri.appendQueryParameter(key, newValue);
return newUri.build();
}
Kotlin & clean, so you don't have to refactor before code review:
private fun addQueryParameters(url: String?): String? {
val uri = URI(url)
val queryParams = StringBuilder(uri.query.orEmpty())
if (queryParams.isNotEmpty())
queryParams.append('&')
queryParams.append(URLEncoder.encode("$QUERY_PARAM=$param", Xml.Encoding.UTF_8.name))
return URI(uri.scheme, uri.authority, uri.path, queryParams.toString(), uri.fragment).toString()
}
An update to Adam's answer considering tryp's answer too. Don't have to instantiate a String in the loop.
public static URI appendUri(String uri, Map<String, String> parameters) throws URISyntaxException {
URI oldUri = new URI(uri);
StringBuilder queries = new StringBuilder();
for(Map.Entry<String, String> query: parameters.entrySet()) {
queries.append( "&" + query.getKey()+"="+query.getValue());
}
String newQuery = oldUri.getQuery();
if (newQuery == null) {
newQuery = queries.substring(1);
} else {
newQuery += queries.toString();
}
URI newUri = new URI(oldUri.getScheme(), oldUri.getAuthority(),
oldUri.getPath(), newQuery, oldUri.getFragment());
return newUri;
}
Related
I am able to create order using square(v2/locations/location_id/orders)api and getting order id. But I am not able to get this order details and also how I can see this created order on square dashboard? please help me.
I am using the below method for doing it:
public CreateOrderResponse createOrder(String locationId, CreateOrderRequest body) throws ApiException {
Object localVarPostBody = body;
// verify the required parameter 'locationId' is set
if (locationId == null) {
throw new ApiException(400, "Missing the required parameter 'locationId' when calling createOrder");
}
// verify the required parameter 'body' is set
if (body == null) {
throw new ApiException(400, "Missing the required parameter 'body' when calling createOrder");
}
// create path and map variables
String localVarPath = "/v2/locations/{location_id}/orders".replaceAll("\\{" + "location_id" + "\\}",
apiClient.escapeString(locationId.toString()));
// query params
List<Pair> localVarQueryParams = new ArrayList<Pair>();
Map<String, String> localVarHeaderParams = new HashMap<String, String>();
Map<String, Object> localVarFormParams = new HashMap<String, Object>();
final String[] localVarAccepts = { "application/json" };
final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);
final String[] localVarContentTypes = { "application/json" };
final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);
String[] localVarAuthNames = new String[] { "oauth2" };
GenericType<CreateOrderResponse> localVarReturnType = new GenericType<CreateOrderResponse>() {
};
CompleteResponse<CreateOrderResponse> completeResponse = (CompleteResponse<CreateOrderResponse>) apiClient
.invokeAPI(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams,
localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames,
localVarReturnType);
return completeResponse.getData();
}
Thanks
The orders endpoint is only for creating itemized orders for e-commerce transactions. You won't see them anywhere until you charge them, and then you'll see the itemizations for the order in your dashboard with the transaction.
I am looking for a way how to get app versionCode and VersionName from google play with package name via java app in PC.
I have seen: https://androidquery.appspot.com/ but it not working anymore and also https://code.google.com/archive/p/android-market-api/ started to making problems and also stopped working, and it requer device ID.
Can you help me with some simple solution or API for this?
Very important, i need versionCode and VersionName and VersionName is relatively easy to get by parsing html google play app site. The versionCode is very important.
There is no official Google Play API, Playstore uses an internal protobuf API which is not documented and not open. IMHO, you could :
use an open source library that reverse engineer the API
scrap apk download sites that have already extracted this information (most likely via the same protobuf Google Play API)
Note that there is a Google Play developer API but you can't list your apks, versions, apps. It's essentially used to manage the app distribution, reviews, edits etc..
Google play internal API
play-store-api Java library
This library uses Google Play Store protobuf API (undocumented and closed API) and requires an email/password to generate a token that can be reused to play with the API :
GplaySearch googlePlayInstance = new GplaySearch();
DetailsResponse response = googlePlayInstance.getDetailResponse("user#gmail.com",
"password", "com.facebook.katana");
AppDetails appDetails = response.getDocV2().getDetails().getAppDetails();
System.out.println("version name : " + appDetails.getVersionString());
System.out.println("version code : " + appDetails.getVersionCode());
with this method :
public DetailsResponse getDetailResponse(String email,
String password,
String packageName) throws IOException, ApiBuilderException {
// A device definition is required to log in
// See resources for a list of available devices
Properties properties = new Properties();
try {
properties.load(getClass().getClassLoader().getSystemResourceAsStream("device-honami" +
".properties"));
} catch (IOException e) {
System.out.println("device-honami.properties not found");
return null;
}
PropertiesDeviceInfoProvider deviceInfoProvider = new PropertiesDeviceInfoProvider();
deviceInfoProvider.setProperties(properties);
deviceInfoProvider.setLocaleString(Locale.ENGLISH.toString());
// Provide valid google account info
PlayStoreApiBuilder builder = new PlayStoreApiBuilder()
.setDeviceInfoProvider(deviceInfoProvider)
.setHttpClient(new OkHttpClientAdapter())
.setEmail(email)
.setPassword(password);
GooglePlayAPI api = builder.build();
// We are logged in now
// Save and reuse the generated auth token and gsf id,
// unless you want to get banned for frequent relogins
api.getToken();
api.getGsfId();
// API wrapper instance is ready
return api.details(packageName);
}
device-honami.properties is device property file that is required to identify device characteristics. You have some device.properties file sample here
The OkHttpClientAdapter can be found here
Dependencies used to run this example :
allprojects {
repositories {
...
maven { url 'https://jitpack.io' }
}
}
dependencies {
compile 'com.github.yeriomin:play-store-api:0.19'
compile 'com.squareup.okhttp3:okhttp:3.8.1'
}
Scrap third part apk download sites
http://apk-dl.com
You could get the version name & version code from http://apk-dl.com (of course unofficial) by scraping the page with jsoup for the required package name :
String packageName = "com.facebook.katana";
Document doc = Jsoup.connect("http://apk-dl.com/" + packageName).get();
Elements data = doc.select(".file-list .mdl-menu__item");
if (data.size() > 0) {
System.out.println("full text : " + data.get(0).text());
Pattern pattern = Pattern.compile("(.*)\\s+\\((\\d+)\\)");
Matcher matcher = pattern.matcher(data.get(0).text());
if (matcher.find()) {
System.out.println("version name : " + matcher.group(1));
System.out.println("version code : " + matcher.group(2));
}
}
https://apkpure.com
Another possibility is scrapping https://apkpure.com :
String packageName = "com.facebook.katana";
Elements data = Jsoup.connect("https://apkpure.com/search?q=" + packageName)
.userAgent("Mozilla")
.get().select(".search-dl .search-title a");
if (data.size() > 0) {
Elements data2 = Jsoup.connect("https://apkpure.com" + data.attr("href"))
.userAgent("Mozilla")
.get().select(".faq_cat dd p");
if (data2.size() > 0) {
System.out.println(data2.get(0).text());
Pattern pattern = Pattern.compile("Version:\\s+(.*)\\s+\\((\\d+)\\)");
Matcher matcher = pattern.matcher(data2.get(0).text());
if (matcher.find()) {
System.out.println("version name : " + matcher.group(1));
System.out.println("version code : " + matcher.group(2));
}
}
}
https://api-apk.evozi.com
Also, https://api-apk.evozi.com has an internal JSON api but :
sometimes it doesn't work (return Ops, APK Downloader got access denied when trying to download) mostly for non popular app
it has mechanism in place against scraping bot (random token generated in JS with a random variable name)
The following is returning the version name and code with https://api-apk.evozi.com FWIW :
String packageName = "com.facebook.katana";
String data = Jsoup.connect("https://apps.evozi.com/apk-downloader")
.userAgent("Mozilla")
.execute().body();
String token = "";
String time = "";
Pattern varPattern = Pattern.compile("dedbadfbadc:\\s+(\\w+),");
Pattern timePattern = Pattern.compile("t:\\s+(\\w+),");
Matcher varMatch = varPattern.matcher(data);
Matcher timeMatch = timePattern.matcher(data);
if (varMatch.find()) {
Pattern tokenPattern = Pattern.compile("\\s*var\\s*" + varMatch.group(1) + "\\s*=\\s*'(.*)'.*");
Matcher tokenMatch = tokenPattern.matcher(data);
if (tokenMatch.find()) {
token = tokenMatch.group(1);
}
}
if (timeMatch.find()) {
time = timeMatch.group(1);
}
HttpClient httpclient = HttpClients.createDefault();
HttpPost httppost = new HttpPost("https://api-apk.evozi.com/download");
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("t", time));
params.add(new BasicNameValuePair("afedcfdcbdedcafe", packageName));
params.add(new BasicNameValuePair("dedbadfbadc", token));
params.add(new BasicNameValuePair("fetch", "false"));
httppost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
HttpResponse response = httpclient.execute(httppost);
JsonElement element = new JsonParser().parse(EntityUtils.toString(response.getEntity()));
JsonObject result = element.getAsJsonObject();
if (result.has("version") && result.has("version_code")) {
System.out.println("version name : " + result.get("version").getAsString());
System.out.println("version code : " + result.get("version_code").getAsInt());
} else {
System.out.println(result);
}
Implementation
You could implement it on a backend of yours that communicates directly with your Java application, this way you could maintain the process of retrieving version code/name if one of the above method fails.
If you are only interested in your own apps, a cleaner solution would be :
to set up a backend which will store all your current app version name / version code
all developer/publisher in your company could share a publish task (gradle task) which will use the Google Play developer API to publish apk and that gradle task would include a call to your backend to store the version code / version name entry when the app is published. The main goal would be to automate the whole publication with storage of the app metadata on your side.
Apart from using JSoup, we can alternatively do pattern matching for getting the app version from playStore.
To match the latest pattern from google playstore ie
<div class="BgcNfc">Current Version</div><span class="htlgb"><div><span class="htlgb">X.X.X</span></div>
we first have to match the above node sequence and then from above sequence get the version value. Below is the code snippet for same:
private String getAppVersion(String patternString, String inputString) {
try{
//Create a pattern
Pattern pattern = Pattern.compile(patternString);
if (null == pattern) {
return null;
}
//Match the pattern string in provided string
Matcher matcher = pattern.matcher(inputString);
if (null != matcher && matcher.find()) {
return matcher.group(1);
}
}catch (PatternSyntaxException ex) {
ex.printStackTrace();
}
return null;
}
private String getPlayStoreAppVersion(String appUrlString) {
final String currentVersion_PatternSeq = "<div[^>]*?>Current\\sVersion</div><span[^>]*?>(.*?)><div[^>]*?>(.*?)><span[^>]*?>(.*?)</span>";
final String appVersion_PatternSeq = "htlgb\">([^<]*)</s";
String playStoreAppVersion = null;
BufferedReader inReader = null;
URLConnection uc = null;
StringBuilder urlData = new StringBuilder();
final URL url = new URL(appUrlString);
uc = url.openConnection();
if(uc == null) {
return null;
}
uc.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; WindowsNT 5.1; en-US; rv1.8.1.6) Gecko/20070725 Firefox/2.0.0.6");
inReader = new BufferedReader(new InputStreamReader(uc.getInputStream()));
if (null != inReader) {
String str = "";
while ((str = inReader.readLine()) != null) {
urlData.append(str);
}
}
// Get the current version pattern sequence
String versionString = getAppVersion (currentVersion_PatternSeq, urlData.toString());
if(null == versionString){
return null;
}else{
// get version from "htlgb">X.X.X</span>
playStoreAppVersion = getAppVersion (appVersion_PatternSeq, versionString);
}
return playStoreAppVersion;
}
I got this solved through this. Hope that helps.
Jsoup takes too long, its inefficient, for short easy way with pattermatching:
public class PlayStoreVersionChecker {
public String playStoreVersion = "0.0.0";
OkHttpClient client = new OkHttpClient();
private String execute(String url) throws IOException {
okhttp3.Request request = new Request.Builder()
.url(url)
.build();
Response response = client.newCall(request).execute();
return response.body().string();
}
public String getPlayStoreVersion() {
try {
String html = execute("https://play.google.com/store/apps/details?id=" + APPIDHERE!!! + "&hl=en");
Pattern blockPattern = Pattern.compile("Current Version.*([0-9]+\\.[0-9]+\\.[0-9]+)</span>");
Matcher blockMatch = blockPattern.matcher(html);
if(blockMatch.find()) {
Pattern versionPattern = Pattern.compile("[0-9]+\\.[0-9]+\\.[0-9]+");
Matcher versionMatch = versionPattern.matcher(blockMatch.group(0));
if(versionMatch.find()) {
playStoreVersion = versionMatch.group(0);
}
}
} catch (IOException e) {
e.printStackTrace();
}
return playStoreVersion;
}
}
public class Store {
private Document document;
private final static String baseURL = "https://play.google.com/store/apps/details?id=";
public static void main(String[] args) {
}
public Store(String packageName) {
try {
document = Jsoup.connect(baseURL + packageName).userAgent("Mozilla/5.0 (Windows NT 6.1; WOW64; rv:64.0) Gecko/20100101 Firefox/64.0").get();
} catch (IOException ex) {
ex.printStackTrace();
}
}
public String getTitle() {
return document.select("h1.AHFaub > span").text();
}
public String getDeveloper() {
return document.selectFirst("span.UAO9ie > a").text();
}
public String getCategory() {
Elements elements = document.select("span.UAO9ie > a");
for (Element element : elements) {
if (element.hasAttr("itemprop")) {
return element.text();
}
}
return null;
}
public String getIcon() {
return document.select("div.xSyT2c > img").attr("src");
}
public String getBigIcon() {
return document.select("div.xSyT2c > img").attr("srcset").replace(" 2x", "");
}
public List<String> getScreenshots() {
List<String> screenshots = new ArrayList<>();
Elements img = document.select("div.u3EI9e").select("button.Q4vdJd").select("img");
for (Element src : img) {
if (src.hasAttr("data-src")) {
screenshots.add(src.attr("data-src"));
} else {
screenshots.add(src.attr("src"));
}
}
return screenshots;
}
public List<String> getBigScreenshots() {
List<String> screenshots = new ArrayList<>();
Elements img = document.select("div.u3EI9e").select("button.Q4vdJd").select("img");
for (Element src : img) {
if (src.hasAttr("data-src")) {
screenshots.add(src.attr("data-srcset").replace(" 2x", ""));
} else {
screenshots.add(src.attr("srcset").replace(" 2x", ""));
}
}
return screenshots;
}
public String getDescription() {
return document.select("div.DWPxHb > span").text();
}
public String getRatings() {
return document.select("div.BHMmbe").text();
}
}
Imports
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
This script will return
Category (Personalization for example)
Developer Name
App Icon
App Name
Screenshots (Thumbnail and Full preview)
Description
You can also check the full source code here
I have bellow url :
http://www.example.com/api/Video/GetListMusicRelated/0/0/null/105358/0/0/10/null/null
This section is Fixed and unchangeable:
http://www.example.com/api/Video/GetListMusicRelated/
I set parameter to this url like bellow :
http://www.example.com/api/Video/GetListMusicRelated/25/60/jim/105358/20/1/5/null/null
OR :
http://www.example.com/api/Video/GetListMusicRelated/0/0/null/105358,5875,85547/0/0/10/null/null
How I can write for this url a url builder ?
If you want to create an UrlBuilder using the builder pattern, it could be done like this:
public class UrlBuilder {
private final String root;
private int myParam1;
private String myParam2;
public UrlBuilder(final String root) {
this.root = root;
}
public UrlBuilder myParam1(int myParam1) {
this.myParam1 = myParam1;
return this;
}
public UrlBuilder myParam2(String myParam2) {
this.myParam2 = myParam2;
return this;
}
public URL build() throws MalformedURLException {
return new URL(
String.format("%s/%d/%s", root, myParam1, myParam2)
);
}
}
Then you will be able to create your URL as next
URL url = new UrlBuilder("http://www.example.com/api/Video/GetListMusicRelated")
.myParam1(25)
.myParam2("jim")
.build();
NB: This only shows the idea, so I used fake parameter's name and incorrect number of parameters, please note that you are supposed to have 6 parameters and set the proper names.
try this...
URL domain = new URL("http://example.com");
URL url = new URL(domain + "/abcd/abcd");
I am working on a news app. I have 5 categories of news sections. Each tab or section, calls to a different URL and has a separate table in the local database, hence a different URI(using a ContentProvider), when retrieving local data.
I have one AsyncTask that services all the requests. It determines which url or uri to call based on the instance of the class passed to it. All the tabs/sections/fragments/classes inherit from a common base class..
Now, I will like to change the AsyncTask to an IntentService, so I can use the AlarmManager class. I have noticed that, there seems to be no easy way of passing an object via intents.
I need a way of determining which particular class of the 5 classes called the IntentService, so the appropriate action is taken.
This class is called when the instance of the class is to be determined:
public class GetURL {
public static URL GetURL(TabsSuperClass tabs)
{
URL url = null;
try {
if(tabs instanceof CultureFrag)
{
final String baseUri = "http://content.guardianapis.com/search?";
Uri uriBuilder = Uri.parse(baseUri)
.buildUpon()
.appendQueryParameter("section", "culture|local|music|books|society")
.appendQueryParameter("order-by", "newest")
.appendQueryParameter("use-date", "published")
.appendQueryParameter("show-fields", "trailText,thumbnail")
.appendQueryParameter("page", String.valueOf(TabsSuperClass.pageSize))
.appendQueryParameter("page-size", "10")
.appendQueryParameter("api-key", "Test-Key")
.build();
url = new URL(uriBuilder.toString());
}
else if(tabs instanceof LifeStyleFrag)
{
final String baseUri = "http://content.guardianapis.com/search?";
Uri uriBuilder = Uri.parse(baseUri)
.buildUpon()
.appendQueryParameter("section", "lifeandstyle|education|fashion|help")
.appendQueryParameter("order-by", "newest")
.appendQueryParameter("use-date", "published")
.appendQueryParameter("show-fields", "trailText,thumbnail")
.appendQueryParameter("page", String.valueOf(LifeStyleFrag.pageSize))
.appendQueryParameter("page-size", "10")
.appendQueryParameter("api-key", "Test-Key")
.build();
url = new URL(uriBuilder.toString());
}
else if(tabs instanceof ScienceFrag)
{
final String baseUri = "http://content.guardianapis.com/search?";
Uri uriBuilder = Uri.parse(baseUri)
.buildUpon()
.appendQueryParameter("section", "science|environment|technology|business")
.appendQueryParameter("order-by", "newest")
.appendQueryParameter("use-date", "published")
.appendQueryParameter("show-fields", "trailText,thumbnail")
.appendQueryParameter("page", String.valueOf(ScienceFrag.pageSize))
.appendQueryParameter("page-size", "10")
.appendQueryParameter("api-key", "Test-Key")
.build();
url = new URL(uriBuilder.toString());
}
else if(tabs instanceof SportFrag)
{
final String baseUri = "http://content.guardianapis.com/search?";
Uri uriBuilder = Uri.parse(baseUri)
.buildUpon()
.appendQueryParameter("section", "sport|football")
.appendQueryParameter("order-by", "newest")
.appendQueryParameter("use-date", "published")
.appendQueryParameter("show-fields", "trailText,thumbnail")
.appendQueryParameter("page", String.valueOf(SportFrag.pageSize))
.appendQueryParameter("page-size", "10")
.appendQueryParameter("api-key", "Test-Key")
.build();
url = new URL(uriBuilder.toString());
}
else if(tabs instanceof WorldFrag)
{
final String baseUri = "http://content.guardianapis.com/search?";
Uri uriBuilder = Uri.parse(baseUri)
.buildUpon()
.appendQueryParameter("section", "world|opinion|media|us-news|australia-news|uk-news")
.appendQueryParameter("order-by", "newest")
.appendQueryParameter("use-date", "published")
.appendQueryParameter("show-fields", "trailText,thumbnail")
.appendQueryParameter("page", String.valueOf(WorldFrag.pageSize))
.appendQueryParameter("page-size", "10")
.appendQueryParameter("api-key", "Test-Key")
.build();
url = new URL(uriBuilder.toString());
}
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
return url;
}
public static Uri GetContentUri(TabsSuperClass tabs)
{
Uri uri = null;
if(tabs instanceof CultureFrag)
{
return NewsContract.CONTENT_URI_CULTURE;
}
else if(tabs instanceof LifeStyleFrag)
{
return NewsContract.CONTENT_URI_LIFESTYLE;
}
else if(tabs instanceof ScienceFrag)
{
return NewsContract.CONTENT_URI_SCIENCE;
}
else if(tabs instanceof SportFrag)
{
return NewsContract.CONTENT_URI_SPORT;
}
else if(tabs instanceof WorldFrag)
{
return NewsContract.CONTENT_URI_WORLD;
}
return uri;
}
}
urlConnection = (HttpURLConnection)GetURL.GetURL(_fragment).openConnection();
An instance where this class is called is here, when I am inserting data into the table of the class which called
private void InsertIntoTable(List<NewsFacade> data) {
for (NewsFacade facade :
data) {
ContentValues values = new ContentValues();
values.put(NewsContract.DataContract.COLUMN_NAME_DATE, facade.getDate());
values.put(NewsContract.DataContract.COLUMN_NAME_CONTENT, facade.getText());
values.put(NewsContract.DataContract.COLUMN_NAME_TAG, facade.getTag());
byte[] image = EncodeImage(facade.getThumb());
values.put(NewsContract.DataContract.COLUMN_NAME_THUMB, image);
values.put(NewsContract.DataContract.COLUMN_NAME_TITLE, facade.getTitle());
values.put(NewsContract.DataContract.COLUMN_NAME_WEBADDRESS, facade.getWebAddress());
_fragment.mResolver.insert(GetURL.GetContentUri(_fragment), values);
}
}
I need a way of determining which particular class of the 5 classes called the IntentService, so the appropriate action is taken.
Put an extra on the Intent that you pass to startActivity() that indicates what the IntentService should do. You get a copy of that Intent in onHandleIntent() in the IntentService, so you can retrieve the extra and take appropriate steps based upon its value.
At the top of the activity I add:-
private final static String THIS_ACTIVITY = "AddProductToShopActivity";
for the intent I add:
intent.putExtra("CALLER", THIS_ACTIVITY);
In the started activity :-
final String caller = getIntent().getStringExtra("Caller");
I am using org.springframework.web.util.UriTemplate and I am trying to match this uri template:
http://{varName1}/path1/path2/{varName2}/{varName3}/{varName4}
with the following uri:
http://hostname/path1/path2/design/99999/product/schema/75016TC806AA/TC806AA.tar
Currently I get the following uri variables:
{varName1=hostname, varName2=design/99999/product/schema, varName3=75016TC806AA,varName4=TC806AA.tar}
But I would like to get the following uri variables:
{varName1=hostname, varName2=design varName3=99999, varName4=product/schema/75016TC806AA/TC806AA.tar}
I tried to use wildcards as * or + in my template, but that doesn't seems to work:
http://{varName1}/path1/path2/{varName2}/{varName3}/{varName4*}
http://{varName1}/path1/path2/{varName2}/{varName3}/{+varName4}
Edited
String url = http://localhost/path1/path2/folder1/folder2/folder3/folder4/folder5
UriTemplate uriTemplate = new UriTemplate(urlTemplateToMatch);
Map<String, String> uriVariables = uriTemplate.match(url);
String urlTemplateToMatch1 = http://{varName1}/path1/path2/{varName2}/{varName3}/{varName4}
uriVariables1 = {varName1=localhost, varName2=folder1/folder2/folder3, varName3=folder4, varName4=folder5}
String urlTemplateToMatch2 = http://{varName1}/test1/test2/{varName2:.*?}/{varName3:.*?}/{varName4}
uriVariables2 = {varName1=localhost, varName2:.*?=folder1/folder2/folder3, varName3:.*?=folder4, varName4=folder5}
String urlTemplateToMatch3 = http://{varName1}/test1/test2/{varName2:\\w*}/{varName3:.\\w*}/{varName4}
uriVariables3 = {varName1=localhost, varName2:\w*=folder1/folder2/folder3, varName3:\w*=folder4, varName4=folder5}
Try with:
http://{varName1}/path1/path2/{varName2:.*?}/{varName3:.*?}/{varName4}
or may be
http://{varName1}/path1/path2/{varName2:\\w*}/{varName3:\\w*}/{varName4}
Edit
#RunWith(BlockJUnit4ClassRunner.class)
public class UriTemplateTest {
private String URI = "http://hostname/path1/path2/design/99999/product/schema/75016TC806AA/TC806AA.tar";
private String TEMPLATE_WORD = "http://{varName1}/path1/path2/{varName2:\\w*}/{varName3:\\w*}/{varName4}";
private String TEMPLATE_RELUCTANT = "http://{varName1}/path1/path2/{varName2:.*?}/{varName3:.*?}/{varName4}";
private Map<String, String> expected;
#Before
public void init() {
expected = new HashMap<String, String>();
expected.put("varName1", "hostname");
expected.put("varName2", "design");
expected.put("varName3", "99999");
expected.put("varName4", "product/schema/75016TC806AA/TC806AA.tar");
}
#Test
public void testTemplateWord() {
testTemplate(TEMPLATE_WORD);
}
#Test
public void testTemplateReluctant() {
testTemplate(TEMPLATE_RELUCTANT);
}
private void testTemplate(String template) {
UriTemplate ut = new UriTemplate(template);
Map<String, String> map = ut.match(URI);
Assert.assertEquals(expected, map);
}
}