I want to use Rally Rest Toolkit java to get all iterations between 2014-06-01 and 2014-06-08,then get all tasks under these iterations.How can I?
Any help would be great! Many Thanks!
To get tasks of iteration that falls within certain dates use this syntax:
taskRequest.setQueryFilter(new QueryFilter("Iteration.StartDate", ">=", "2014-06-01").and(new QueryFilter("Iteration.EndDate", "<=", "2014-06-08")));
and set workspace of the request:
taskRequest.setWorkspace("123456); //use your ObjectID
so that child iterations (from all projects in the workspace) with the same start and end dates are included in the results.
public static void main(String[] args) throws URISyntaxException, IOException {
String host = "https://rally1.rallydev.com";
String username = "user#co.com";
String password = "psw";
String workspaceRef = "/workspace/12352608129";
String applicationName = "ExampleFindTasks";
RallyRestApi restApi = null;
try{
restApi = new RallyRestApi(
new URI(host),
username,
password);
restApi.setApplicationName(applicationName);
QueryRequest taskRequest = new QueryRequest("Task");
taskRequest.setFetch(new Fetch("Name","FormattedID","Iteration","Project"));
taskRequest.setLimit(1000);
taskRequest.setScopedDown(true);
taskRequest.setScopedUp(false);
taskRequest.setWorkspace(workspaceRef);
taskRequest.setQueryFilter(
new QueryFilter("Iteration.StartDate", ">=", "2014-06-01").and(
new QueryFilter("Iteration.EndDate", "<=", "2014-06-08")));
QueryResponse taskQueryResponse = restApi.query(taskRequest);
int numberOfResults = taskQueryResponse.getTotalResultCount();
System.out.println(numberOfResults);
if(numberOfResults > 0){
for (int i=0;i<numberOfResults;i++){
JsonObject taskJsonObject = taskQueryResponse.getResults().get(i).getAsJsonObject();
System.out.println("Name: " + taskJsonObject.get("Name") + " " + "FormattedID: " +
taskJsonObject.get("FormattedID"));
JsonElement iteration = taskJsonObject.get("Iteration");
JsonElement project = taskJsonObject.get("Project");
try{
JsonObject iterationObject = iteration.getAsJsonObject().getAsJsonObject();
JsonObject projectObject = project.getAsJsonObject().getAsJsonObject();
System.out.println(iterationObject.get("Name"));
System.out.println(projectObject.get("Name"));
}
catch (java.lang.IllegalStateException ise) {
System.out.println("ise");
}
}
}
}
finally{
if (restApi != null) {
restApi.close();
}
}
}
Related
This is the code I have written for JUnit Testing for positive and negative testing.
#Test
public void getMaintenenceIntervalsByMetadataOKTest() throws Exception {
MultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>();
params.set("vinModelYear", "2016");
params.set("vinModelCode", "1633F6");
params.set("vinEngineCode", "CZTA");
params.set("interval", "100000");
params.set("vinTransmissionCode", "");
params.set("importerNumber", "");
params.set("makeCode", "V");
params.set("descriptionText", "");
params.set("languageCode", "en-US");
params.set("dealerCode", "408083");
mvc.perform(get("/upg-admin-controller/maintenence-intervals-by-metadata")
.contentType(MediaType.APPLICATION_JSON)
.params(params))
.andExpect(status().isAccepted());
}
#Test
public void getMaintenenceIntervalsByMetadata400Test()
throws Exception {
MultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>();
params.set("vinModelYear", "2000");
params.set("vinModelCode", "8727R9");
params.set("vinEngineCode", "GTAV");
params.set("interval", "100000");
params.set("vinTransmissionCode", "");
params.set("importerNumber", "");
params.set("makeCode", "T");
params.set("descriptionText", "");
params.set("languageCode", "sp-MX");
params.set("dealerCode", "120021");
mvc.perform(get("/upg-admin-controller/maintenence-intervals-by-metadata")
.contentType(MediaType.APPLICATION_JSON)
.params(params))
.andExpect(status().isBadRequest());
}
Error:
Error: java.lang.AssertionError: Status expected:<202> but was:<400>.
I have been trying to fix it but cannot find a solution. Using EclEmma extension on Eclipse. (sorry if the code is out of line. The text box is small it splits one line of code into two lines.)
Also this is the Controller code that I am working with that has the QueryParams.
#RequestMapping(value = "/maintenence-intervals-by-metadata", method = RequestMethod.GET)
public ResponseEntity<List<AdminMaintenanceIntervalReponse>> findMaintenenceIntervalsByMetadata( #QueryParam("modelYear") String modelYear,
#QueryParam("modelCode") String modelCode, #QueryParam("engineCode") String engineCode, #QueryParam("interval") String interval ,
#QueryParam("transmissionCode") String transmissionCode , #QueryParam("importer") String importer, #QueryParam("make") String make,
#QueryParam("descriptionText") String descriptionText, #QueryParam("languageCode") String languageCode, #QueryParam("dealerCode") String dealerCode, #QueryParam("brand") String Brand) throws MPMSException {
LOGGER.log(Level.INFO, "Entered UPGAdminServiceController, getAllMaintenenceIntervalsByMetadata");
LOGGER.log(Level.INFO, "modelYear =" + modelYear +" modelCode = " + modelCode +" engineCode = " + engineCode +" interval = " + interval + "transmissionCode = " + transmissionCode + "importer = " + importer + "make = " + make + "descriptionText = " + descriptionText);
List<AdminMaintenanceIntervalReponse> allMaintenanceIntervalsList = new ArrayList<AdminMaintenanceIntervalReponse>();
try{
Integer modelYearParam = null;
if (modelYear!=null){
modelYearParam = Integer.parseInt(modelYear);
}
Integer intervalParam = null;
if (interval!=null){
intervalParam = Integer.parseInt(interval);
}
String modelCodeParam = null;
if (modelCode!=null){
modelCodeParam = String.valueOf(modelCode);
}
String engineCodeParam = null;
if (engineCode!=null){
engineCodeParam = String.valueOf(engineCode);
}
String transmissionCodeParam = null;
if (transmissionCode!=null){
transmissionCodeParam = String.valueOf(transmissionCode);
}
Integer importerParam = null;
if (importer!=null){
importerParam = Integer.parseInt(importer);
}
String makeParam = null;
if (make!=null){
makeParam = String.valueOf(make);
}
if (descriptionText!=null){
String.valueOf(descriptionText);
}
allMaintenanceIntervalsList = upgAdminMaintenanceCalcService.findMaintenanceIntervalsByMetadata(modelYearParam, modelCodeParam, engineCodeParam, intervalParam, transmissionCodeParam, importerParam, makeParam, descriptionText, languageCode, dealerCode);
} catch(MPMSException e){
throw e;
} catch (Exception e) {
throw new MPMSException(ErrorConstants.UNKNOWN.getErrorCode(), "No Data Available", ErrorConstants.UNKNOWN.toString(), e);
}
return new ResponseEntity<List<AdminMaintenanceIntervalReponse>>(allMaintenanceIntervalsList, HttpStatus.OK);
}
Can someone please help me correct this issue.
Your /maintenence-intervals-by-metadata endpoint has the following query parameters:
#QueryParam("modelYear")
#QueryParam("modelCode")
#QueryParam("engineCode")
#QueryParam("interval")
#QueryParam("transmissionCode")
#QueryParam("importer")
#QueryParam("make")
#QueryParam("descriptionText")
#QueryParam("languageCode")
#QueryParam("dealerCode")
#QueryParam("brand")
But your test is submitting a [GET] request to /maintenence-intervals-by-metadata with the following named parameters:
params.set("vinModelYear", "2016");
params.set("vinModelCode", "1633F6");
params.set("vinEngineCode", "CZTA");
params.set("interval", "100000");
params.set("vinTransmissionCode", "");
params.set("importerNumber", "");
params.set("makeCode", "V");
params.set("descriptionText", "");
params.set("languageCode", "en-US");
params.set("dealerCode", "408083");
So, the query params you supply do not match the query params expected by the /maintenence-intervals-by-metadata endpoint. There are name mismatches:
modelYear vs. vinModelYear
modelCode vs. vinModelCode
... etc
And at least one query parameter is not supplied: the endpoint declares #QueryParam("brand") but you are not supplying a parameter named "brand".
I suspect the message associated with the 400 error might include something like: Required String parameter '...' is not present.
If you change your invocation such that every one of the query parameters defined by the /maintenence-intervals-by-metadata endpoint has a supplied parameter value of the correct type (a String) then I think the 400 will no longer occur.
Hi I am writing a web server to be hosted locally that will have latitude and longitude posted in the URL/URI from an android device and this will be used as search criteria in an SQL Select query to retrieve the 5 clostes train stations.
I have made the code work with the hard coded Longitude and Latitude but now need to add in the functionality of it being dynamically added form teh adnroid device using the Post/Get functions, unfortunately i have never used get/post so dont know where to start.
Below is my code from all Classes in the web server, as said it all works hardcoded but now needs to accept input from an android device and return the same expected results. Thanks
public class WebServer {
static String jArray = "";
public static void main(String[] args) {
try{
HttpServer server = HttpServer.create(new InetSocketAddress(8080),0);
server.createContext("/",new HttpHandler(){
public void handle(HttpExchange he) throws IOException{
try {
jArray = sqlConnector.train(jArray);
} catch (Throwable e) {
e.printStackTrace();
}
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(he.getResponseBody()));
System.out.println("Processing Request");
he.sendResponseHeaders(200, 0);
String output = "<html><head></head><body><p>" + jArray + "</p></body></html>";
bw.write(output);
bw.close();
}
});
server.start();
System.out.println("Started up . . .");
}
catch (IOException ioe){
System.err.println("problems Starting Webserver: " + ioe);
}
}
}
public class sqlConnector {
public static String train(String jArray) throws Exception{
PreparedStatement s = null;
try
{
Connection c = DriverManager.getConnection("jdbc:sqlite:C:/Users/Colin/trainstations.db");
s = c.prepareStatement("SELECT Latitude, Longitude, StationName,( 3959 * acos(cos(radians(53.4355)) * cos(radians(Latitude)) * cos(radians(Longitude) - radians(-3.0508)) + sin(radians(53.4355)) * sin(radians(Latitude )))) AS distance FROM stations ORDER BY distance ASC LIMIT 0,5;");
ResultSet rs = s.executeQuery();
jArray = jsonConverter.convertResultSetIntoJSON(rs, jArray);
}
catch (SQLException se)
{
se.printStackTrace();
}
return jArray;
}
}
public class jsonConverter {
public static String convertResultSetIntoJSON(ResultSet rs, String jArray) throws Exception {
JSONArray jsonArray = new JSONArray();
while (rs.next()) {
int total_rows = rs.getMetaData().getColumnCount();
JSONObject obj = new JSONObject();
for (int i = 0; i < total_rows; i++) {
String columnName = rs.getMetaData().getColumnLabel(i + 1).toString();
Object columnValue = rs.getObject(i + 1);
obj.put(columnName, columnValue);
}
jsonArray.put(obj);
}
jArray = jsonArray.toString();
return jArray;
}
}
I am currently connected to another webserver that hosts the same data and is fully functinal and after the port number its format is as follows
/stations?lat=" + lat + "&lng=" + lng);
where lat and lng are my variable taken using GPS
The process would be like this:
1) Parse the Parameters from query String he.getRequestURI().getQuery()
/**
* returns the url parameters in a map
* #param query
* #return map
*/
public static Map<String, String> queryToMap(String query){
Map<String, String> result = new HashMap<String, String>();
for (String param : query.split("&")) {
String pair[] = param.split("=");
if (pair.length>1) {
result.put(pair[0], pair[1]);
}else{
result.put(pair[0], "");
}
}
return result;
}
2) Pass these parameters into select method
public static String train(String jArray, double lat, double long) throws Exception{
3) Use it in your statement
s = c.prepareStatement("SELECT Latitude, Longitude, StationName,
( 3959 * acos(cos(radians(?)) * cos(radians(Latitude))
* cos(radians(Longitude) - radians(?)) + sin(radians(?))
* sin(radians(Latitude ))))
AS distance FROM stations ORDER BY distance ASC LIMIT 0,5;");
s.setDouble(1, lat);
s.setDouble(2, long);
s.setDouble(3, lat);
And finally
4) Fix your code.
use a Database connection pool instead of connecting to the database for every call
use try-with-resource to automatically close ResultSet, PreparedStatement, Connection (even in case of Errors)
Hope that helps as a rough guideline :-)
Hello Elasticsearch Friends.
I have a Problem with my settings and mappings in Elasticsearch Java API. I configured my Index and set the mapping and settings. My indexname is "orange11", type "profile". I want that when I'm typing in my search inputField after just 2 or 3 letters Elasticsearch gives me some results. I've read something about analyzer, mapping and all this stuff and so I tried out.
This is my IndexService code:
#Service
public class IndexService {
private Node node;
private Client client;
#Autowired
public IndexService(Node node) throws Exception {
this.node = node;
client = this.node.client();
ImmutableSettings.Builder indexSettings = ImmutableSettings.settingsBuilder();
indexSettings.put("orange11.analysis.filter.autocomplete_filter.type", "edge_ngram");
indexSettings.put("orange11.analysis.filter.autocomplete_filter.min.gram", 1);
indexSettings.put("orange11.analysis.filter.autocomplete_filter.max_gram", 20);
indexSettings.put("orange11.analysis.analyzer.autocomplete.type", "custom");
indexSettings.put("orange11.analysis.analyzer.tokenizer", "standard");
indexSettings.put("orange11.analysis.analyzer.filter", new String[]{"lowercase", "autocomplete_filter"});
IndicesExistsResponse res = client.admin().indices().prepareExists("orange11").execute().actionGet();
if (res.isExists()) {
DeleteIndexRequestBuilder delIdx = client.admin().indices().prepareDelete("orange11");
delIdx.execute().actionGet();
}
CreateIndexRequestBuilder createIndexRequestBuilder = client.admin().indices().prepareCreate("orange11").setSettings(indexSettings);
// MAPPING GOES HERE
XContentBuilder mappingBuilder = jsonBuilder().startObject().startObject("profile").startObject("properties")
.startObject("name").field("type", "string").field("analyzer", "autocomplete").endObject()
.endObject()
.endObject();
System.out.println(mappingBuilder.string());
createIndexRequestBuilder.addMapping("profile ", mappingBuilder);
createIndexRequestBuilder.execute().actionGet();
List<Accounts> accountsList = transformJsonFileToJavaObject();
//Get Data from jsonMap() function into a ListMap.
//List<Map<String, Object>> dataFromJson = jsonToMap();
createIndex(accountsList);
}
public List<Accounts> transformJsonFileToJavaObject() throws IOException {
ObjectMapper mapper = new ObjectMapper();
List<Accounts> list = mapper.readValue(new File("/Users/lucaarchidiacono/IdeaProjects/moap2/MP3_MoapSampleBuild/data/index/testAccount.json"), TypeFactory.defaultInstance().constructCollectionType(List.class, Accounts.class));
return list;
}
public void createIndex(List<Accounts> accountsList) {
for (int i = 0; i < accountsList.size(); ++i) {
Map<String, Object> accountMap = new HashMap<String, Object>();
accountMap.put("id", accountsList.get(i).getId());
accountMap.put("isActive", accountsList.get(i).isActive());
accountMap.put("balance", accountsList.get(i).getBalance());
accountMap.put("age", accountsList.get(i).getAge());
accountMap.put("eyeColor", accountsList.get(i).getEyeColor());
accountMap.put("name", accountsList.get(i).getName());
accountMap.put("gender", accountsList.get(i).getGender());
accountMap.put("company", accountsList.get(i).getCompany());
accountMap.put("email", accountsList.get(i).getEmail());
accountMap.put("phone", accountsList.get(i).getPhone());
accountMap.put("address", accountsList.get(i).getAddress());
accountMap.put("about", accountsList.get(i).getAbout());
accountMap.put("greeting", accountsList.get(i).getGreeting());
accountMap.put("favoriteFruit", accountsList.get(i).getFavoriteFruit());
accountMap.put("url", accountsList.get(i).getUrl());
//Request an Index for indexObject. Set the index specification such as indexName, indexType and ID.
IndexRequestBuilder indexRequest = client.prepareIndex("orange11", "profile", Integer.toString(i)).setSource(accountMap);
//Execute the indexRequest and get the result in indexResponse.
IndexResponse indexResponse = indexRequest.execute().actionGet();
if (indexResponse != null && indexResponse.isCreated()) {
//Print out result of indexResponse
System.out.println("Index has been created !");
System.out.println("------------------------------");
System.out.println("Index name: " + indexResponse.getIndex());
System.out.println("Type name: " + indexResponse.getType());
System.out.println("ID: " + indexResponse.getId());
System.out.println("Version: " + indexResponse.getVersion());
System.out.println("------------------------------");
} else {
System.err.println("Index creation failed.");
}
}
}
}
Every time I wanna run this code I become this exception:
Caused by: org.elasticsearch.index.mapper.MapperParsingException: Root type mapping not empty after parsing! Remaining fields: [profile : {properties={name={analyzer=autocomplete, type=string}}}]
at org.elasticsearch.index.mapper.DocumentMapperParser.parse(DocumentMapperParser.java:278)
at org.elasticsearch.index.mapper.DocumentMapperParser.parseCompressed(DocumentMapperParser.java:192)
at org.elasticsearch.index.mapper.MapperService.parse(MapperService.java:449)
at org.elasticsearch.index.mapper.MapperService.merge(MapperService.java:307)
at org.elasticsearch.cluster.metadata.MetaDataCreateIndexService$2.execute(MetaDataCreateIndexService.java:391)
I don't know how to continue, because I don't see any '.' missing in my indexSettings. Sorry for my bad English.
Change min.gram to min_gram.
(See indexSettings.put("orange11.analysis.filter.autocomplete_filter.min.gram", 1);)
I am trying to delete the accounts from Gigya DB, so we can reuse them to test our login function through Gigya. It seems the UID required for deletion come from login, so how am I suppose to do it in Java?
As mentioned by Ilan, firstly you'll need to include the Gigya Java SDK.
You can then look up the UID using either the Identity Access or Identity Query Tool within Gigya console and use the follow code to delete the account:
// delete user record
GSRequest deleteAccountRequest = new GSRequest(apiKey, secretKey, "accounts.deleteAccount");
//deleteAccountRequest.setAPIDomain("eu1.gigya.com"); // enable this if you're using the EU data centre
deleteAccountRequest.setUseHTTPS(true);
deleteAccountRequest.setParam("UID", uid);
GSResponse deleteAccountResponse = deleteAccountRequest.send();
if(deleteAccountResponse.getErrorCode()==0)
{
}
else
{
System.out.println("deleteAccountResponse failure: " + deleteAccountResponse.getLog());
}
Alternatively, if you want to delete users in batch, you can run a search using accounts.search and delete all the users within the results set:
int limit = 100;
String query = "select UID from accounts where ... " + limit; // add your query here i.e. email = 'someone#example.com'
String cursorId = "";
int objectsCount = limit;
GSRequest searchRequest;
ArrayList<String> uidList = new ArrayList<String>();
// send request
do
{
// check if we have an open cursor
if(cursorId.length() > 0)
{
// run next request in cursor
// set up request
searchRequest = new GSRequest(apiKey, secretKey, "accounts.search");
//searchRequest.setAPIDomain("eu1.gigya.com");
//searchRequest.setUseHTTPS(true);
// set timeout
searchRequest.setParam("timeout", 60000);
// set cursor id
searchRequest.setParam("cursorId", cursorId);
} else {
// run new request and open cursor
// set up request
searchRequest = new GSRequest(apiKey, secretKey, "accounts.search");
//searchRequest.setAPIDomain("eu1.gigya.com");
//searchRequest.setUseHTTPS(true);
// set timeout
searchRequest.setParam("timeout", 60000);
// set query
searchRequest.setParam("query", query);
// open cursor
searchRequest.setParam("openCursor", true);
}
GSResponse searchResponse = searchRequest.send();
if(searchResponse.getErrorCode()==0)
{
GSArray uids = new GSArray();
uids = searchResponse.getArray("results", uids);
for(int i=0; i<uids.length(); i++)
{
String uid;
try {
// retrieve uid and add to list of uids
uid = uids.getObject(i).getString("UID");
uidList.add(uid);
} catch (GSKeyNotFoundException e) {
}
}
cursorId = searchResponse.getString("nextCursorId", "");
objectsCount = searchResponse.getInt("objectsCount", 0);
}
else
{
System.out.println("searchRequest failure: " + searchResponse.getLog());
}
}
while (objectsCount >= limit);
for(int i=0; i<uidList.size(); i++)
{
String uid;
try {
uid = uidList.get(i);
// delete user record
GSRequest deleteAccountRequest = new GSRequest(apiKey, secretKey, "accounts.deleteAccount");
//deleteAccountRequest.setAPIDomain("eu1.gigya.com");
deleteAccountRequest.setUseHTTPS(true);
deleteAccountRequest.setParam("UID", uid);
GSResponse deleteAccountResponse = deleteAccountRequest.send();
if(deleteAccountResponse.getErrorCode()==0)
{
}
else
{
System.out.println("deleteAccountResponse failure: " + deleteAccountResponse.getLog());
}
} catch (Exception e) {
}
}
I have a URL and I need to get the value of v from this URL.
Here is my URL: http://www.youtube.com/watch?v=_RCIP6OrQrE
How can I do that?
I think the one of the easiest ways out would be to parse the string returned by URL.getQuery() as
public static Map<String, String> getQueryMap(String query) {
String[] params = query.split("&");
Map<String, String> map = new HashMap<String, String>();
for (String param : params) {
String name = param.split("=")[0];
String value = param.split("=")[1];
map.put(name, value);
}
return map;
}
You can use the map returned by this function to retrieve the value keying in the parameter name.
If you're on Android, you can do this:
Uri uri = Uri.parse(url);
String v = uri.getQueryParameter("v");
I have something like this:
import org.apache.http.NameValuePair;
import org.apache.http.client.utils.URIBuilder;
private String getParamValue(String link, String paramName) throws URISyntaxException {
List<NameValuePair> queryParams = new URIBuilder(link).getQueryParams();
return queryParams.stream()
.filter(param -> param.getName().equalsIgnoreCase(paramName))
.map(NameValuePair::getValue)
.findFirst()
.orElse("");
}
I wrote this last month for Joomla Module when implementing youtube videos (with the Gdata API). I've since converted it to java.
Import These Libraries
import java.net.URL;
import java.util.regex.*;
Copy/Paste this function
public String getVideoId( String videoId ) throws Exception {
String pattern = "^(https?|ftp|file)://[-a-zA-Z0-9+&##/%?=~_|!:,.;]*[-a-zA-Z0-9+&##/%=~_|]";
Pattern p = Pattern.compile(pattern);
Matcher m = p.matcher(videoId);
int youtu = videoId.indexOf("youtu");
if(m.matches() && youtu != -1){
int ytu = videoId.indexOf("http://youtu.be/");
if(ytu != -1) {
String[] split = videoId.split(".be/");
return split[1];
}
URL youtube = new URL(videoId);
String[] split = youtube.getQuery().split("=");
int query = split[1].indexOf("&");
if(query != -1){
String[] nSplit = split[1].split("&");
return nSplit[0];
} else return split[1];
}
return null; //throw something or return what you want
}
URL's it will work with
http://www.youtube.com/watch?v=k0BWlvnBmIE (General URL)
http://youtu.be/k0BWlvnBmIE (Share URL)
http://www.youtube.com/watch?v=UWb5Qc-fBvk&list=FLzH5IF4Lwgv-DM3CupM3Zog&index=2 (Playlist URL)
Import these libraries
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
Similar to the verisimilitude, but with the capabilities of handling multivalue parameters. Note: I've seen HTTP GET requests without a value, in this case the value will be null.
public static List<NameValuePair> getQueryMap(String query)
{
List<NameValuePair> queryMap = new ArrayList<NameValuePair>();
String[] params = query.split(Pattern.quote("&"));
for (String param : params)
{
String[] chunks = param.split(Pattern.quote("="));
String name = chunks[0], value = null;
if(chunks.length > 1) {
value = chunks[1];
}
queryMap.add(new BasicNameValuePair(name, value));
}
return queryMap;
}
Example:
GET /bottom.gif?e235c08=1509896923&%49%6E%...
Using pure Java 8
Assumming you want to extract param "v" from url:
String paramV = Stream.of(url.split("?")[1].split("&"))
.map(kv -> kv.split("="))
.filter(kv -> "v".equalsIgnoreCase(kv[0]))
.map(kv -> kv[1])
.findFirst()
.orElse("");
Assuming the URL syntax will always be http://www.youtube.com/watch?v= ...
String v = "http://www.youtube.com/watch?v=_RCIP6OrQrE".substring(31);
or disregarding the prefix syntax:
String url = "http://www.youtube.com/watch?v=_RCIP6OrQrE";
String v = url.substring(url.indexOf("v=") + 2);
I believe we have a better approach to answer this question.
1: Define a function that returns Map values.
Here we go.
public Map<String, String> getUrlValues(String url) throws UnsupportedEncodingException {
int i = url.indexOf("?");
Map<String, String> paramsMap = new HashMap<>();
if (i > -1) {
String searchURL = url.substring(url.indexOf("?") + 1);
String params[] = searchURL.split("&");
for (String param : params) {
String temp[] = param.split("=");
paramsMap.put(temp[0], java.net.URLDecoder.decode(temp[1], "UTF-8"));
}
}
return paramsMap;
}
2: Call your function surrounding with a try catch block
Here we go
try {
Map<String, String> values = getUrlValues("https://example.com/index.php?form_id=9&page=1&view_id=78");
String formId = values.get("form_id");
String page = values.get("page");
String viewId = values.get("view_id");
Log.d("FormID", formId);
Log.d("Page", page);
Log.d("ViewID", viewId);
} catch (UnsupportedEncodingException e) {
Log.e("Error", e.getMessage());
}
If you are using Jersey (which I was, my server component needs to make outbound HTTP requests) it contains the following public method:
var multiValueMap = UriComponent.decodeQuery(uri, true);
It is part of org.glassfish.jersey.uri.UriComponent, and the javadoc is here. Whilst you may not want all of Jersey, it is part of the Jersey common package which isn't too bad on dependencies...
I solved the problem like this
public static String getUrlParameterValue(String url, String paramName) {
String value = "";
List<NameValuePair> result = null;
try {
result = URLEncodedUtils.parse(new URI(url), UTF_8);
value = result.stream().filter(pair -> pair.getName().equals(paramName)).findFirst().get().getValue();
System.out.println("--------------> \n" + paramName + " : " + value + "\n");
} catch (URISyntaxException e) {
e.printStackTrace();
}
return value;
}
this will work for all sort of youtube url :
if url could be
youtube.com/?v=_RCIP6OrQrE
youtube.com/v/_RCIP6OrQrE
youtube.com/watch?v=_RCIP6OrQrE
youtube.com/watch?v=_RCIP6OrQrE&feature=whatever&this=that
Pattern p = Pattern.compile("http.*\\?v=([a-zA-Z0-9_\\-]+)(?:&.)*");
String url = "http://www.youtube.com/watch?v=_RCIP6OrQrE";
Matcher m = p.matcher(url.trim()); //trim to remove leading and trailing space if any
if (m.matches()) {
url = m.group(1);
}
System.out.println(url);
this will extract video id from your url
further reference
My solution mayble not good
String url = "https://www.youtube.com/watch?param=test&v=XcHJMiSy_1c&lis=test";
int start = url.indexOf("v=")+2;
// int start = url.indexOf("list=")+5; **5 is length of ("list=")**
int end = url.indexOf("&", start);
end = (end == -1 ? url.length() : end);
System.out.println(url.substring(start, end));
// result: XcHJMiSy_1c
work fine with:
https://www.youtube.com/watch?param=test&v=XcHJMiSy_1c&lis=test
https://www.youtube.com/watch?v=XcHJMiSy_1c
public static String getQueryMap(String query) {
String[] params = query.split("&");
for (String param : params) {
String name = param.split("=")[0];
if ("YourParam".equals(name)) {
return param.split("=")[1];
}
}
return null;
}