Is there a method can convert & delimited String to a java class?
Foo foo = Foo.fromString("name1=a&name2=b");
I am coding the twitter api: https://developer.twitter.com/en/docs/basics/authentication/api-reference/access_token. the response is
I need need a function do the blow things for me.
String respnse = "oauth_token=6253282-eWudHldSbIaelX7swmsiHImEL4KinwaGloHANdrY&oauth_token_secret=2EEfA6BG3ly3sR3RjE0IBSnlQu4ZrUzPiYKmrkVU&user_id=6253282&screen_name=twitterapi";
String [] resParas = respnse.split("&");
for(String respara : resParas){
if(respara.indexOf("oauth_token=")>=0){
int index = "oauth_token=".length();
access_token = respara.substring(index);
}else if(respara.indexOf("oauth_token_secret=")>=0){
int index = "oauth_token_secret=".length();
access_token_secret = respara.substring(index);
}else if(respara.indexOf("user_id=")>=0){
int index = "user_id=".length();
user_id = respara.substring(index);
}else if(respara.indexOf("screen_name=")>=0){
int index = "screen_name=".length();
screen_name = respara.substring(index);
}
}
You can use UriComponentsBuilder for this:
MultiValueMap<String, String> parameters = UriComponentsBuilder
.fromUriString("http://twitter.com/oauth?oauth_token=6253282-eWudHldSbIaelX7swmsiHImEL4KinwaGloHANdrY&oauth_token_secret=2EEfA6BG3ly3sR3RjE0IBSnlQu4ZrUzPiYKmrkVU&user_id=6253282&screen_name=twitterapi")
.build()
.getQueryParams();
Will give you a map with all params:
{oauth_token=[6253282-eWudHldSbIaelX7swmsiHImEL4KinwaGloHANdrY], oauth_token_secret=[2EEfA6BG3ly3sR3RjE0IBSnlQu4ZrUzPiYKmrkVU], user_id=[6253282], screen_name=[twitterapi]}
Related
This question already has answers here:
Java List<string> not adding to list after Arrays.asList() has been used
(3 answers)
Closed 4 months ago.
My controller class:
#PostMapping(value = "/uniqueUrl")
#ResponseBody
public ResponseEntity<MyResponse> urlGenerator(#RequestBody MyRequest myRequest){
log.info("Request for url : ", myRequest);
MyResponse myResponse= this.generateUrlService.urlGenerator(myRequest);
log.info("generateUniqueUrl response: ", myResponse.getLongUniqueUrlList());
return ResponseEntity.accepted().body(myResponse);
}
MyRequest class:
#Data
public class MyRequestimplements Serializable {
#NotNull(message = "Url cannot be null or empty")
private String url;
#NotNull(message = "count cannot be null or empty")
private int cound;
}
My service implemantation :
#Override
public myResponse urlGenerator(MyRequest myRequest) {
log.info("urlGenerator started..");
myUrlRequestValidator.validate(myRequest);
String longUrl = myRequest.getUrl();
int count = myRequest.getCount();
List<String> uniqueUrlList = Arrays.asList(new String[count]);
for (String string : uniqueUrlList) {
string = longUrl + "/?";
for (int i = 0; i < rand.nextInt(11)+4; i++) {
string += letters.get(rand.nextInt(35));
}
uniqueUrlList.add(string);
log.info(string);
}
MyResponse response = new MyResponse();
response.setLongUniqueUrlList(uniqueUrlList);
return response;
}
MyResponse class:
#Data
public class MyResponse extends BaseResponse {
private List<String> longUniqueUrlList;
private List<String> shortUrlList;
}
In the method where my Controller and Service class is as follows, the result of uniqueUrlList returns null. I want to add each string formed by the add method to the list, but it does not add it. Can you help me where am I going wrong?
edit1 : When I change the random url generation and adding to the list in this way, it does not enter the for loop, or when I do not change the loop and only define it as an arraylist, it gives a Null error in the add method. How can I solve this? It's such an easy thing, but I don't understand why I can't do it?
List<String> uniqueUrlList = new ArrayList<String>();
String string = null;
for ( int j = 0; j < count; j++) {
string = longUrl + "/?";
for (int i = 0; i < rand.nextInt(11)+4; i++) {
string += letters.get(rand.nextInt(35));
}
uniqueUrlList.add(string);
log.info(string);
}
}
It is null because your List<String> uniqueUrlList is initialized with Arrays.asList which are fixed in size and unmodifiable, as specified in the Javadoc. The Arrays.asList(new String[count]) is also empty as there are no elements inside the new String[count].
Instead you should initialize it with a new ArrayList<String>():
List<String> uniqueUrlList = new ArrayList<String>();
Where you can then modify the list as you please, using a loop to add to your uniqueUrlList as many as myRequest.getCount() times.
You should initialize a list by
List<String> uniqueUrlList = new ArrayList<>();
I am currently working on a Java application where I have an AsyncTask function get data from an API, then have a line reader and string builder create a large string, which I then pass to the postExecute function where I convert that string into a JSON object. I have tried creating a function that takes the string before post execute and replaces all null with "N/A", I have also tried checking in the String builder function but neither seem to make any changes to the null value. Here is an example of what the code looks like. I believe the error occurs when The string is converted into the JSON Object. This is a school project and I am not allowed to use external libraries.
String Builder:
BufferedReader reader = new BufferedReader(new InputStreamReader(httpClient.getInputStream()));
StringBuilder builder = new StringBuilder();
String line;
while((line = reader.readLine()) != null) {
if (line.contains(null) || line.contains(""))
line += "N/A";
else
continue;
builder.append(line + "\n");
}
replaceNull Function:
public String removeUnwantedVal(String message) {
if (message.contains("null")) {
String replacement = "N/A";
message.replaceAll(null, replacement);
}
return message;
}
Post Execute JSON Object:
protected void onPostExecute(String message) {
TextView tv = findViewById(R.id.display);
System.out.println(message);
try {
JSONObject jsonAddress = new JSONObject(message);
// DISPLAY INFORMATION
String requesterIP = jsonAddress.getString("requester-ip");
String execTime = jsonAddress.getString("execution-time");
ipInfo.setIPAndTime(requesterIP, execTime);
// GEOGRAPHY
JSONObject geo = jsonAddress.getJSONObject("geo");
String countryName = geo.getString("country-name");
String capital = geo.getString("capital");
String iso = geo.getString("country-iso-code");
String city = geo.getString("city");
double longitude = geo.getDouble("longitude");
double latitude = geo.getDouble("latitude");
location = new Location(countryName, capital, iso, city, longitude, latitude);
// CURRENCY
JSONObject currency = jsonAddress.getJSONObject("currency");
String currencyNativeName = currency.getString("native-name");
String currencyCode = currency.getString("code");
String currencyName = currency.getString("name");
String currencySymbol = currency.getString("symbol");
Currency = new Currency(currencyNativeName, currencyCode, currencyName, currencySymbol);
// ASN
JSONObject asn = jsonAddress.getJSONObject("asn");
String asnName = asn.getString("name");
String asnDomain = asn.getString("domain");
String asnOrganization = asn.getString("organization");
String asnCode = asn.getString("asn");
String asnType = asn.getString("type");
ASN = new ASN(asnName, asnDomain, asnOrganization, asnCode, asnType);
// TIMEZONE
JSONObject timezone = jsonAddress.getJSONObject("timezone");
String timezoneName = timezone.getString("microsoft-name");
String dateTime = timezone.getString("date-time");
String ianaName = timezone.getString("iana-name");
Timezone = new Timezone(timezoneName, dateTime, ianaName);
// SECURITY
JSONObject security = jsonAddress.getJSONObject("security");
boolean isCrawler = security.getBoolean("is-crawler");
boolean isProxy = security.getBoolean("is-proxy");
boolean isTor = security.getBoolean("is-tor");
Security = new Security(isCrawler, isProxy, isTor);
container = new IPContainer(ipInfo, Currency, location, Security, ASN, Timezone);
tv.setText(container.displayGeneral());
} catch (JSONException e) {
tv.setText(e.toString());
e.printStackTrace();
}
}
I have resolved the issue. When I was getting the code I thought that null values could not be displayed, this was incorrect. The problem was that I was trying to create an object out of null, sometimes the value came back as null instead of as an object. Sorry, beginner coder :)
Hi.
I'm making an app that receives data from bluetooth by using stringbuilder
And makes it slice for using another activity.
The image shows what i want to make.
Q1. What should i use c->d, d->e ?
Q2. There will be a lot of data, I want to know the way to simplify this sequence
******************** edited ********************
I have practiced by adding value to Arraylist.
But in String Array, there is no .get(), so i couldn't access to element's length.
public static ArrayList<String> randomValue = new ArrayList<>();
public static int iDistance=0, xIAngle=0, yIAngle=0, zIAngle=0;
public static String distance, xAngle, yAngle, zAngle;
randomValue.add("12345090080070");
randomValue.add("15640080085071");
randomValue.add("16542070084074");
randomValue.add("12645080087078");
randomValue.add("21345084081060");
randomValue.add("14785078075065");
randomValue.add("13155079077077");
randomValue.add("14623080078078");
randomValue.add("14918086080078");
randomValue.add("15684085082080");
for (int i=0; i<randomValue.size(); i++){
String a = randomValue.get(i);
String distance = a.substring(0,5);
String xAngle = a.substring(5,8);
String yAngle = a.substring(8,11);
String zAngle = a.substring(11,14);
//String to int
iDistance = Integer.parseInt(distance);
xIAngle = Integer.parseInt(xAngle);
yIAngle = Integer.parseInt(yAngle);
zIAngle = Integer.parseInt(zAngle);
}
It seems like you are just stuck on finding the equivalent of get for a string array. To access an element in an array, the syntax is array[I], so if you were using a string array, this line:
String a = randomValue.get(i);
would have been:
String a = randomValue[i];
The code for your sequence of transformations can be shortened with Streams:
// this is the sequence of transformation starting with the sting builder "a"
List<String> randomValueWithLength14 =
Arrays.stream(a.toString().split(";")).filter(x -> x.length() == 14)
.collect(Collectors.toList());
// this is the for loop shown in your code
for (int i=0; i<randomValueWithLength14.size(); i++){
String s = randomValueWithLength14.get(i);
String distance = a.substring(0,5);
String xAngle = s.substring(5,8);
String yAngle = s.substring(8,11);
String zAngle = s.substring(11,14);
//String to int
iDistance = Integer.parseInt(distance);
xIAngle = Integer.parseInt(xAngle);
yIAngle = Integer.parseInt(yAngle);
zIAngle = Integer.parseInt(zAngle);
}
I'd like to retrieve data from string based on params from template.
For example:
given string -> "some text, var=20 another part param=45"
template -> "some text, var=${var1} another part param=${var2}"
result -> var1 = 20; var2 = 45
How could I achive that result in Java. Are there some libs or I need to use regex?
I tried different template processors, but they don't have needed functionality, I need something like inverse to them.
I hope below sample will serve your purpose -
String strValue = "some text, var=20 another part param=45";
String strTemplate = "some text, var=${var1} another part param=${var2}";
ArrayList<String> wildcards = new ArrayList<String>();
StringBuffer outputBuffer = new StringBuffer();
Pattern pat1 = Pattern.compile("(\\$\\{\\w*\\})");
Matcher mat1 = pat1.matcher(strTemplate);
while (mat1.find())
{
wildcards.add(mat1.group(1).replaceAll("\\$", "").replaceAll("\\{", "").replaceAll("\\}", ""));
strTemplate = strTemplate.replace(mat1.group(1), "(\\w*)");
}
if(wildcards!= null && wildcards.size() > 0)
{
Pattern pat2 = Pattern.compile(strTemplate);
Matcher mat2 = pat2.matcher(strValue);
if (mat2.find())
{
for(int i=0;i<wildcards.size();i++)
{
outputBuffer.append(wildcards.get(i)).append(" = ");
outputBuffer.append(mat2.group(i+1));
if(i != wildcards.size()-1)
{
outputBuffer.append("; ");
}
}
}
}
System.out.println(outputBuffer.toString());
I am naming all of these one by one. Is there a method that takes less space?
public class Matt{
PImage matt,
imgLS1, imgLS2, imgLS3, imgRS1, imgRS2, imgRS3,
imgLSB1, imgLSB2, imgLSB3, imgRSB1, imgRSB2, imgRSB3,
imgLW1, imgLW2, imgLW3, imgRW1, imgRW2, imgRW3,
imgLWB1, imgLWB2, imgLWB3, imgRWB1, imgRWB2, imgRWB3;
public Matt(){
imgLS1 = loadImage("./Images/Matt/MattLS1.png");
imgLS2 = loadImage("./Images/Matt/MattLS2.png");
imgLS3 = loadImage("./Images/Matt/MattLS3.png");
imgRS1 = loadImage("./Images/Matt/MattRS1.png");
imgRS2 = loadImage("./Images/Matt/MattRS2.png");
imgRS3 = loadImage("./Images/Matt/MattRS3.png");
imgLSB1 = loadImage("./Images/Matt/MattLSB1.png");
imgLSB2 = loadImage("./Images/Matt/MattLSB2.png");
imgLSB3 = loadImage("./Images/Matt/MattLSB3.png");
imgRSB1 = loadImage("./Images/Matt/MattRSB1.png");
imgRSB2 = loadImage("./Images/Matt/MattRSB2.png");
imgRSB3 = loadImage("./Images/Matt/MattRSB3.png");
imgLW1 = loadImage("./Images/Matt/MattLW1.png");
imgLW2 = loadImage("./Images/Matt/MattLW2.png");
imgLW3 = loadImage("./Images/Matt/MattLW3.png");
imgRW1 = loadImage("./Images/Matt/MattRW1.png");
imgRW2 = loadImage("./Images/Matt/MattRW2.png");
imgRW3 = loadImage("./Images/Matt/MattRW3.png");
imgLWB1 = loadImage("./Images/Matt/MattLWB1.png");
imgLWB2 = loadImage("./Images/Matt/MattLWB2.png");
imgLWB3 = loadImage("./Images/Matt/MattLWB3.png");
imgRWB1 = loadImage("./Images/Matt/MattRWB1.png");
imgRWB2 = loadImage("./Images/Matt/MattRWB2.png");
imgRWB3 = loadImage("./Images/Matt/MattRWB3.png");
}
}
Put your images in a Map<String,PImage>, organizing the map by image suffix. As far as accessing the images is concerned, this approach may be slightly less convenient/efficient than using variables directly, but it will save you a lot of space:
static final String[] suffixes = new String[] {"LS1", "LS2", "LS3", ..., "RWB3"};
Map<String,PImage> images = new HashMap<String,PImage>();
public Matt() {
for (String suffix : suffixes) {
PImage image = loadImage("./Images/Matt/Matt"+suffix+".png");
images.put(suffix, image);
}
}
Since the "LS", etc., seem to have semantic meaning, I'd suggest a variation of the solution by #dasblinkenlight that uses an enum:
final int N_FILES = 3; // files/position -- could also be a variable
enum Position {
LS, RS, LSB, RSB, LW, RW, LWB, LRB
}
Map<Position, String[]> files = new EnumMap<>(Position.class);
for (Position pos : Position.values()) {
String[] posFiles = new String[N_FILES];
files.put(pos, posFiles);
for (int i = 1; i <= N_FILES; ++i) {
posFiles[i-1] = "./Images/Matt/Matt" + pos.name() + i + ".png";
}
}
Then you can access any element with code like this:
Position p = RS; // or any other value
int index = 0; // 0..(N_FILES-1), corresponding to suffixes 1..N_FILES
String fileName = files.get(p)[i];