URLEncodedUtils is deprecated in Android API 22+. What could I use instead in this code?
I need to change URLEncode.Utils.Format() line.
public String construct() {
return (iftrue? HOSTING_NAME : _NAME) + yDomain
+ (param.size() > 0 ? "?"
+ URLEncodedUtils.format(yParam, "utf-8") : "");
}
You can use java inbuilt method java.net.URLEncoder to construct url with param data. URLEncoder.encode(yParam, "UTF-8")
Change your method and check it.
`public String construct() {
return (iftrue? HOSTING_NAME : _NAME) + yDomain
+ (param.size() > 0 ? "?" + URLEncoder.encode(yParam, "UTF-8"): "");}`
Related
I just have a question in running a Get request based on string urls.
The code below determines the string urls and puts each urls in an array for a table row.
final String URL_CORE = “/test/platform/auth”;
List<String> urls = new ArrayList<>();
rows.forEach(row -> {
final String clientValue = row.getCell("client");
final String uriValue = row.getCell("uri");
final String typeValue = row.getCell("type"));
urls.add(URL_CORE + "?" +
(clientValue.isEmpty ? "" : CLIENT + "=" + clientValue + "&") +
(uriValue.isEmpty ? "" : URI + "=" + uriValue + "&") +
(typeValue.isEmpty ? "" : TYPE + "=" + typeValue);
});
Within the forEach, I have this code where I just want to run the get request for the url string (for each row at a time). It is giving me an erray type expected found and wondering what am I doing wrong?
getRequest(queryParamsList[row]);
It seems by the name that queryParamsList is a List, not an array, so you have to access element by list.get(index) method. If you dont have the index, you can get it by list.indexOf(element)
One of my webservice return below Java string:
[
{
id=5d93532e77490b00013d8862,
app=null,
manufacturer=pearsonEducation,
bookUid=bookIsbn,
model=2019,
firmware=[1.0],
bookName=devotional,
accountLinking=mandatory
}
]
I have the equivalent Java object for the above string. I would like to typecast or convert the above java string into Java Object.
I couldn't type-cast it since it's a String, not an object. So, I was trying to convert the Java string to JSON string then I can write that string into Java object but no luck getting invalid character "=" exception.
Can you change the web service to return JSON?
That's not possible. They are not changing their contracts. It would be super easy if they returned JSON.
The format your web-service returns has it's own name HOCON. (You can read more about it here)
You do not need your custom parser. Do not try to reinvent the wheel.
Use an existing one instead.
Add this maven dependency to your project:
<dependency>
<groupId>com.typesafe</groupId>
<artifactId>config</artifactId>
<version>1.3.0</version>
</dependency>
Then parse the response as follows:
Config config = ConfigFactory.parseString(text);
String id = config.getString("id");
Long model = config.getLong("model");
There is also an option to parse the whole string into a POJO:
MyResponsePojo response = ConfigBeanFactory.create(config, MyResponsePojo.class);
Unfortunately this parser does not allow null values. So you'll need to handle exceptions of type com.typesafe.config.ConfigException.Null.
Another option is to convert the HOCON string into JSON:
String hoconString = "...";
String jsonString = ConfigFactory.parseString(hoconString)
.root()
.render(ConfigRenderOptions.concise());
Then you can use any JSON-to-POJO mapper.
Well, this is definitely not the best answer to be given here, but it is possible, at least…
Manipulate the String in small steps like this in order to get a Map<String, String> which can be processed. See this example, it's very basic:
public static void main(String[] args) {
String data = "[\r\n"
+ " {\r\n"
+ " id=5d93532e77490b00013d8862, \r\n"
+ " app=null,\r\n"
+ " manufacturer=pearsonEducation, \r\n"
+ " bookUid=bookIsbn, \r\n"
+ " model=2019,\r\n"
+ " firmware=[1.0], \r\n"
+ " bookName=devotional, \r\n"
+ " accountLinking=mandatory\r\n"
+ " }\r\n"
+ "]";
// manipulate the String in order to have
String[] splitData = data
// no leading and trailing [ ] - cut the first and last char
.substring(1, data.length() - 1)
// no linebreaks
.replace("\n", "")
// no windows linebreaks
.replace("\r", "")
// no opening curly brackets
.replace("{", "")
// and no closing curly brackets.
.replace("}", "")
// Then split it by comma
.split(",");
// create a map to store the keys and values
Map<String, String> dataMap = new HashMap<>();
// iterate the key-value pairs connected with '='
for (String s : splitData) {
// split them by the equality symbol
String[] keyVal = s.trim().split("=");
// then take the key
String key = keyVal[0];
// and the value
String val = keyVal[1];
// and store them in the map ——> could be done directly, of course
dataMap.put(key, val);
}
// print the map content
dataMap.forEach((key, value) -> System.out.println(key + " ——> " + value));
}
Please note that I just copied your example String which may have caused the line breaks and I think it is not smart to just replace() all square brackets because the value firmware seems to include those as content.
In my opinion, we split the parse process in two step.
Format the output data to JSON.
Parse text by JSON utils.
In this demo code, i choose regex as format method, and fastjson as JSON tool. you can choose jackson or gson. Furthermore, I remove the [ ], you can put it back, then parse it into array.
import com.alibaba.fastjson.JSON;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class SerializedObject {
private String id;
private String app;
static Pattern compile = Pattern.compile("([a-zA-Z0-9.]+)");
public static void main(String[] args) {
String str =
" {\n" +
" id=5d93532e77490b00013d8862, \n" +
" app=null,\n" +
" manufacturer=pearsonEducation, \n" +
" bookUid=bookIsbn, \n" +
" model=2019,\n" +
" firmware=[1.0], \n" +
" bookName=devotional, \n" +
" accountLinking=mandatory\n" +
" }\n";
String s1 = str.replaceAll("=", ":");
StringBuffer sb = new StringBuffer();
Matcher matcher = compile.matcher(s1);
while (matcher.find()) {
matcher.appendReplacement(sb, "\"" + matcher.group(1) + "\"");
}
matcher.appendTail(sb);
System.out.println(sb.toString());
SerializedObject serializedObject = JSON.parseObject(sb.toString(), SerializedObject.class);
System.out.println(serializedObject);
}
}
I have a logging function in CSharp and Java that I use in walking the stack. How do I make each log print to a new line only. Below are my Java and CSharp Functions.
public static void LogFunctionCall(String parameters){
Object trace = Thread.currentThread().getStackTrace()[3];
android.util.Log.i("##################" + trace.toString()+ "", parameters );
}
the java version is this
public static void LogFunctionCall(string parameters,
[System.Runtime.CompilerServices.CallerMemberName] string methodName = "",
[System.Runtime.CompilerServices.CallerFilePath] string sourceFilePath = "",
[System.Runtime.CompilerServices.CallerLineNumber] int sourceLineNumber = 0)
{
var stackFrame = new StackFrame(1);
var callerMethod = stackFrame.GetMethod();
var className = callerMethod.DeclaringType;
System.Diagnostics.Trace.WriteLine("CCCCCCCCCCCCCCCC" + " " + className + " " + methodName + " " + sourceLineNumber + " " + parameters + "\n");
}
I code on a windows machine.
Please where exactly do I need to place the new line character. I tried this
public static void LogFunctionCall(String parameters){
Object trace = Thread.currentThread().getStackTrace()[3];
android.util.Log.i("##################" + trace.toString()+ "", parameters + "\n" );
}
but I still saw some of the logs being clumped up on a single line.
Instead of \n, try \r\n (carriage return and newline). Some text editors will display differently, so the newline may be in there, but whatever app you're using to read the logs might not be displaying it correctly.
You could also try
System.lineSeparator();
I've seen instances where the /n won't work but the lineSep does.
Also, because it hasn't been mentioned, Environment.NewLine will give you the new line character that is configured for the current environment.
I have a Json string like below
String jsonRequestString = "{\"access_code\" : \"9bPbN3\" , "
+ "\"merchant_reference\" : \"123\", \"language\" : \"en\",\"id\" : \"149018273\","
+ "\"merchant_identifier\" : \"gKc\", \"signature\" : \"570fd712af47995468550bec2655d9e23cdb451d\", "
+ "\"command\" : \"VOID\"}";
I have a String variable as
String code = "9bPbN3";
Question, how do I plugin the above string instead of hardcoding it at the below place. i.e. instead of 9bPbN3, I want to use the variable code there.
String jsonRequestString = "{\"access_code\" : \"9bPbN3\" , "
Many Thanks in advance.
If you are struggling to arrange the "'s the correct syntax would be
String jsonRequestString = "{\"access_code\" : \""+code+"\" , ";
Instead of formatting Json string manually, which takes alot of effort, consider using a library or util.
For ex (going to use Jackson library) :
Request re = new Request();
re.setCode(code);
...
ObjectMapper mapper = new ObjectMapper();
String jsonStr = mapper.writeValueAsString(re);
String yourVariable = "xyz";
String jsonRequestString = "{\"access_code\" : \"" + yourVariable + "\" , "
+ "\"merchant_reference\" : \"123\", \"language\" : \"en\",\"id\" : \"149018273\","
+ "\"merchant_identifier\" : \"gKc\", \"signature\" : \"570fd712af47995468550bec2655d9e23cdb451d\", "
+ "\"command\" : \"VOID\"}";
General advice is to avoid crafting a json structure out of vanilla strings. Instead use a json parser/writer library for this operations.
Checkout http://stleary.github.io/JSON-java/index.html / http://stleary.github.io/JSON-java/index.html .
There a various other libraries and tutorials available.
If you don't want to go this direction, use a "known value" placeholder and substitute it. So the full json would contain "access_code" : "##ACCESS_CODE##" and you would Substitute the placeholder with the real value. So your json string would be some kind of a string template.
Another option would be to use the format method like so:
String jsonRequestString = "{\"access_code\" : \"%s\" , "
+ "\"merchant_reference\" : \"123\", \"language\" : \"en\",\"id\" : \"149018273\","
+ "\"merchant_identifier\" : \"gKc\", \"signature\" : \"570fd712af47995468550bec2655d9e23cdb451d\", "
+ "\"command\" : \"VOID\"}";
String code = "9bPbN3";
String result = String.format(jsonRequestString, code);
Notice the "%s" I put in the place of where code would go. When you call the format method with code as a parameter, it puts it where the "%s" was.
I would like to be able to create a live template in Jetbrain's Idea that will log the method's arguments. Let's call it "larg". It would work like:
public void get(String one, String two) {
larg<tab>
to create
public void get(String one, String two) {
log.info("get: one = " + one + " two = " + two);
I'm fine with getting the method name in, but have not figured out how to pull in the method arguments. Any ideas?
I'm 4 years late, but the predefined template soutp pretty much does this using a groovyscript variable.
Here's the groovy script that does what you're looking for
groovyScript("'\"' + _1.collect { it + ' = [\" + ' + it + ' + \"]'}.join(', ') + '\"'", methodParameters())
Looks like it is not currently possible with a live template.
From the Jetbrain's forum:
There is no predefined live template function to do this for you automatically.
You can write a plugin that would provide such a function.
this is my groovy script
groovyScript("import com.intellij.psi.*;import com.intellij.psi.util.PsiTreeUtil; def file = PsiDocumentManager.getInstance(_editor.project).getPsiFile(_editor.document); PsiMethod method = PsiTreeUtil.findElementOfClassAtOffset(file, _editor.caretModel.offset, PsiMethod.class, false); PsiParameter[] parameters = method == null ? PsiParameter.EMPTY_ARRAY : method.parameterList.parameters; return parameters.size() == 0 ? '' : '\"' + method.name + ' : ' + parameters.collect { def prefix = it.name + ' = '; def type = it.type; return type instanceof PsiArrayType ? type.componentType instanceof PsiPrimitiveType ? prefix + '\" + java.util.Arrays.toString(' + it.name + ')' : prefix + '\" + java.util.Arrays.deepToString(' + it.name + ')' : prefix + '\" + ' + it.name }.join(' + \", ')", methodParameters())
In Android Studio in Kotlin I use this to log classname, methodname and parameters.
I use my name as tag to easily filter in logcat. I use these mainly for debugging, I don't commit these messages with my name.
Log.d("MYNAME", "$CLASS_NAME$:$METHOD_NAME$: $PARAMETERS$")
And then the parameters are defined as follows.
CLASS_NAME : kotlinClassName()
METHOD_NAME : kotlinFunctionName()
PARAMETERS : groovyScript("'' + _1.collect { it + ' = $' + it}.join(', ') ", functionParameters())
This would be the result if used in the main activity
fun aFunctionWithParameters( first: Int, second: String, third: ArrayList<String>){
Log.d("MYNAME", "MainActivity:aFunctionWithParameters: first = $first, second = $second, third = $third")
}
I based my solution on Rob's answer and edited it to my needs.