Writing an if statement in Ceylon - ceylon

I have tasked myself with writing a file writer in Ceylon and in the process of doing so I have been hit by the crushing difficulty of writing an if statement in Ceylon, that will be allowed to pass when facing the mighty Wizard of Type Correctness on the narrow Bridge of Compilation in the far far land of Ceylon:
The error I get is "Error:(10, 1) ceylon: incorrect syntax: missing EOF at 'if'"
This is my if statement (the first line is line 10):
if (is Nil fileResource || is File fileResource) {
File file = createFileIfNil(fileResource);
value writer = file.Overwriter();
//writer.writeLine("Hello, World!");
} else {
print("hello");
}
EDIT:
this is my if statement updated according to Bastien Jansens recommendation. The error, however, remains the same :(
Path folderPath = parsePath("""C:\Users\Jon\Auchitect\POSTtoFile""");
Path filePath = folderPath.childPath("BPset.json.txt");
FResource fileResource = filePath.resource;
if (is Nil|File fileResource) {
File file = createFileIfNil(fileResource);
value writer = file.Overwriter();
//writer.writeLine("Hello, World!");
} else {
print("hello");
}
This is the full source code of my application:
import ceylon.http.server { newServer, startsWith, Endpoint, Request, Response }
import ceylon.io { SocketAddress }
import ceylon.file { Path, parsePath, File, createFileIfNil, FResource = Resource }
// let's create a file with "hello world":
Path folderPath = parsePath("""C:\Users\Jon\Auchitect\POSTtoFile""");
Path filePath = folderPath.childPath("BPset.json.txt");
FResource fileResource = filePath.resource;
if (is Nil|File fileResource) {
File file = createFileIfNil(fileResource);
value writer = file.Overwriter();
//writer.writeLine("Hello, World!");
} else {
print("hello");
}
shared void runServer() {
//create a HTTP server
value server = newServer {
//an endpoint, on the path /hello
Endpoint {
path = startsWith("/postBPset");
//handle requests to this path
function service(Request request, Response response) {
variable String logString;
variable String jsonString;
variable String contentType;
contentType = request.contentType
else "(not specified)";
logString = "Received " + request.method.string + " request \n"
+ "Content type: " + contentType + "\n"
+ "Request method: " + request.method.string + "\n";
jsonString = request.read();
print(logString);
return response;
}
}
};
//start the server on port 8080
server.start(SocketAddress("127.0.0.1",8080));
}

The || operator cannot be used in conjunction with if (is ...), the correct way to achieve what you want is using a union type:
if (is Nil|File fileResource) {
...
}
|| would be valid in the following syntax, but you would lose the refinement (it would only be a boolean expression, not a type refinement):
if (fileResource is Nil || fileResource is File ) {
...
}
The || operator only works on Boolean expressions (which foo is Bar is), whereas is Bar foo is a Boolean condition, which is a different construct. The same applies for exists conditions vs exists operators.
EDIT: oh, and of course you need to put that if statement in a function, toplevel elements can only be declarations (classes, functions or values, if statements are not allowed).

Related

Hook instagram apk using Frida

I wanted to hook some functions from instagram apk using frida, decompiled the apk with
jadx/JEB, one of the functions I wanted to hook was in this:
public static void A00(HGf arg8, I1Y arg9) {
arg8.A0P();
Boolean v0 = arg9.A0v;
if(v0 != null) {
arg8.A0l("about_your_account_bloks_entrypoint_enabled", v0.booleanValue());
}
//some other code here
}
Tried to hook the function with this frida script:
try {
//
let I1X = Java.use("X.I1X")
console.log("this is instance: ", I1X)
console.log(
"these are the methods:: ",
Java.use("X.I1X").class.getDeclaredMethods()
)
I1X.A00.overload().implemention = function (HGf, I1Y) {
console.log("A0l is called")
let ret = this.A0l(str, z)
console.log("A0l ret value is " + ret)
}
} catch (e) {
console.log("failed!" + e)
}
})
this script outputs:
this is instance: <class: X.I1X>
these are the methods::
failed!TypeError: not a function
apparently the A00 here is not a function, so back to jadx in the compiled code there is another class with the same name within same package but consisting of some other code, here it is:
/* renamed from: X.I1x reason: case insensitive filesystem */
/* loaded from: classes7.dex */
public final class C39227I1x {
public C39229I1z A00 = null;
}
apparently Frida is hooking this variable instance A00 In my opinion that is why
it is returning not a function here.
So my question, how can I hook like this situation?
Edit:
the two classes are somewhat different in jadx.

Why does UserAuthExtensions.PopulateFromMap(session, jwtPayload) does not deserialize json values with escape correctly in ServiceStack.Auth?

We want to get the UserName from the ServiceStack session, but we find that the backslashes in the UserName are not deserialized as expected. The UserName has this format 'domainname\username' and serialized in a jwt token this looks like:
{
"typ": "JWT",
"alg": "HS256"
}.{
"iss": "ssjwt",
"iat": 1635952233,
"exp": 1635955833,
"name": "Robin Doe",
"preferred_username": "domainname\\robindoe"
}.[Signature]
After calling:
var sessionFromJwt = JwtAuthProviderReader.CreateSessionFromJwt(req);
userName = sessionFromJwt.UserName;
The userName variable contains the value 'domainname\\robindoe' instead of 'domainname\robindoe'.
After digging in the ServiceStack code, we pin this down to the PopulateFromMap() method in https://github.com/ServiceStack/ServiceStack/blob/36df74a8b1ba7bf06f85262c1155e1425c082906/src/ServiceStack/Auth/UserAuth.cs#L388.
To demonstrate this problem we have written a small program to prove the point:
class Program
{
static void Main(string[] args)
{
var jwtPayload = JsonObject.Parse(#"{
""iss"": ""ssjwt"",
""iat"": 1635952233,
""exp"": 1635955833,
""name"": ""John Doe"",
""preferred_username"": ""domainname\\username""
}");
var session = new AuthUserSession();
// The PopulateFromMap implementation does not deserialize the json values according to json standards
UserAuthExtensions.PopulateFromMap(session, jwtPayload);
// Notice that the session.UserName still has the escape character 'domainname\\username' instead of the expected 'domainname\username'
Console.WriteLine(session.UserName);
// The PopulateFromMap should deserialize also the values, like in test Can_dynamically_parse_JSON_with_escape_chars()
Can_dynamically_parse_JSON_with_escape_chars();
}
private const string JsonCentroid = #"{""place"":{ ""woeid"":12345, ""placeTypeName"":""St\\a\/te"" } }";
// Source: https://github.com/ServiceStack/ServiceStack.Text/blob/master/tests/ServiceStack.Text.Tests/JsonObjectTests.cs
public static void Can_dynamically_parse_JSON_with_escape_chars()
{
var placeTypeName = JsonObject.Parse(JsonCentroid).Object("place").Get("placeTypeName");
if (placeTypeName != "St\\a/te")
throw new InvalidCastException(placeTypeName + " != St\\a/te");
placeTypeName = JsonObject.Parse(JsonCentroid).Object("place").Get<string>("placeTypeName");
if (placeTypeName != "St\\a/te")
throw new InvalidCastException(placeTypeName + " != St\\a/te");
}
}
Why does UserAuthExtensions.PopulateFromMap(session, jwtPayload) does not deserialize json values with escape correctly in ServiceStack.Auth?
The issue is due to enumerating a JsonObject didn't return the same escaped string value as indexing it which has been resolved from this commit.
This change is available from v5.12.1+ that's now available on MyGet.

Batch json strings processing using playframework in Scala

I use API which might either return a single json string, a batch of json strings or the string PROCESSING_TIMEOUT, e.g.:
{"id":123,"field1":"test1"}
or:
{"id":123,"field1":"test1"}
{"id":456,"field2":"test2"}
{"id":789,"field3":"test3"}
or (in case of asynchronous processing timeout in remote API)
PROCESSING_TIMEOUT
In the function getRestContent I want to be able to correcty process all these possible outputs, including also the timeout errors. In the current version of the function I lack the possibility to process batch json strings. I think that the best option would be that the function returns List<JsValue> instead of JsValue.
How can I do this modification using Play Framework.
def getRestContent(url:String,param:String,paramValue:String): JsValue = {
var output : JsValue = null
var httpOutput : String = null
try {
val response: HttpResponse[String] = Http(url).timeout(connTimeoutMs = 10000000, readTimeoutMs = 10000000).param(param,paramValue).asString
httpOutput = response.body
} catch
{
case ex: Exception => {
println("Failed connection with remote API")
}
}
if (!httpOutput.contains("PROCESSING_TIMEOUT") && httpOutput != null)
{
try {
output = Json.parse(httpOutput)
}
catch
{
case ex: Exception => {
println("Failed to process a document")
}
}
}
else
{
println("Asynchronous processing timeout")
}
if (output != null)
{
return output
}
else {
return new JsObject(Map("empty" -> JsNumber(0)))
}
}
Disregarding Play Framework your code is not Scala-flavored in general.
Below is a simple example of how better to approach such task in more Scala-way.
Highlights: use scala.util.Try wrapper to normally work with exceptions in a functional way, use pattern matching and monadic map and other methods of collections.
I hope the code below is self-explanatory. I mimicked the API. It returns Strings and not JSON but your 3 basic cases are sufficiently emulated: single line, multiple lines and exceptional case.
Try to run the program few times and you will see that all 3 cases are handled correctly:
import scala.util.{Failure, Success, Try, Random}
/**
* Created by Alex on 3/10/2016.
*/
object Temp {
case class Item(name:String, value:Int)
object API{
def getTimeOutResponse:String = throw new TimeoutException("no luck this time")
def getSingleLineResponse = "{name: \"Alex\", value: 1}"
def getMultiLineResponse = "{name: \"Alex\", value: 1}\n{name: \"HackerDuck\", value: 2}"
def getRandomResponse = (Math.abs(Random.nextInt() % 3)) match{
case 0 => getTimeOutResponse
case 1 => getSingleLineResponse
case 2 => getMultiLineResponse
}
}
def getResults:List[Item]={
Try(API.getRandomResponse) match{
case Success(s) =>{
s.split("\n").toList.map{item =>
val parts = item.split(", ")
Item(parts(0).replace("{name: ", "").replace("\"", ""), parts(1).replace("value: ", "").replace("}", "").toInt)
}
}
case Failure(_) =>{
println("API timeout happened")
List.empty[Item]
}
}
}
def main(args:Array[String])={
println(getResults)
println(getResults)
println(getResults)
}
}
A sample output from my console:
API timeout happened
List()
List(Item(Alex,1))
List(Item(Alex,1), Item(HackerDuck,2))
Process finished with exit code 0
The code becomes less cluttered without all these if statements and !=null and alike. Also you can streamline conversion of your elements sequence to List in one place.

Unity3d Facebook Response Data parsing

I was able to solve this solution is in the coment
I have problem with parsing data that I get rom Facebook on appRequestCallback.
The request is send and that part is ok. But I need to pars the send data for the internal uses.
the code is this
private void appRequestCallback(FBResult result)
{
Util.Log("appRequestCallback");
if (result != null)
{
var responseObject = Json.Deserialize(result.Text) as Dictionary<string, object>;
object obj = 0;
string resp = (string)responseObject["request"];
Util.Log ("resp : " + resp);
if (responseObject.TryGetValue("cancelled", out obj))
{
Util.Log("Request cancelled");
}
else if (responseObject.TryGetValue("request", out obj))
{
responseObject.TryGetValue("to", out obj);
string[] s = (string[]) obj;
Util.Log ("s: " + s);
AddPopupMessage("Request Sent", ChallengeDisplayTime);
Util.Log("Request sent");
}
}
}
In the console I get this
appRequestCallback
UnityEngine.Debug:Log(Object)
resp: 870884436303337
UnityEngine.Debug:Log(Object)
And then the error
InvalidCastException: Cannot cast from source type to destination type.
MainMenu.appRequestCallback (.FBResult result) (at Assets/Resources/Scripts/MainMenu.cs:482)
Facebook.AsyncRequestDialogPost.CallbackWithErrorHandling (.FBResult result)
Facebook.AsyncRequestString+c__Iterator0.MoveNext ()
The problem is in parsing of to: part of json file and I am not sure why. I have tried to cast it into string, string[], List<>, Array, ArrayList. As I see the problem is that I am not using the good cast type for the to: but I can not figure out what the correct cast type is

How do I pull out the JSON field I want using Jackson TreeNode and JsonNode?

I'm a little stumped why I can't pull the "Type" field out of my JSON stream to make a decision. It seems like this should be so easy.
I have the following JSON that I have as input:
[
{
"Institution":"ABC",
"Facility":"XYZ",
"Make":"Sunrise",
"Model":"Admission",
"SerialNumber":"",
"Revision":"1",
"Type":"ABC_Admission",
"ArchiveData":"<CSV file contents>"
}
]
In my Java I have a try-catch block with a JsonHolder class that implements Serializable to hold the JSON. Here's the Java I currently have:
try {
// Parse and split the input
JsonHolder data = JsonHolder.getField("text", input);
DataExtractor.LOG.info("JsonHolder data= " + data);
TreeNode node = data.getTreeNode();
DataExtractor.LOG.info("node size= " + node.size());
node = node.path("Type");
JsonNode json = (JsonNode) node;
DataExtractor.LOG.info("json= " + json.asText());
// code to decide what to do based on Type found
if (json.asText().equals("ABC_Admission")) {
// do one thing
} else {
// do something else
}
} catch (IOException iox) {
DataExtractor.LOG.error("Error extracting data", iox);
this.collector.fail(input);
}
When I run my code I get the following output (NOTE: I changed my package name where the class is to just for this output display)
25741 [Thread-91-DataExtractor] INFO <proprietary package name>.DataExtractor - JsonHolder data= [
{
"Institution":"ABC",
"Facility":"XYZ",
"Make":"Sunrise",
"Model":"Admission",
"SerialNumber":"",
"Revision":"1",
"Type":"ABC_Admission",
"ArchiveData":"<CSV file contents>"
}
]
25741 [Thread-91-DataExtractor] INFO <proprietary package name>.DataExtractor - node size= 1
25741 [Thread-91-DataExtractor] INFO <proprietary package name>.DataExtractor - json=
As you can see I don't get anything out. I just want to extract the value of the field "Type", so I was expecting to get the value "ABC_Admission" in this case. I would have thought the node path would separate out just that field from the rest of the JSON tree.
What am I doing wrong?
After consulting with another developer I found out the issue is my JSON is inside an array. So, I need to iterate over that array and then pull out the Type field from the object.
The updated code to resolve this is below:
try {
// Parse and split the input
JsonHolder data = JsonHolder.getField("text", input);
DataExtractor.LOG.info("JsonHolder data= " + data);
TreeNode node = data.getTreeNode();
String type = null;
// if this is an array of objects, iterate through the array
// to get the object, and reference the field we want
if (node.isArray()){
ArrayNode ary = (ArrayNode) node;
for (int i = 0; i < ary.size(); ++i) {
JsonNode obj = ary.get(i);
if (obj.has("Type")) {
type = obj.path("Type").asText();
break;
}
}
}
if (type == null) {
// Do something with failure??
}
DataExtractor.LOG.info("json= " + type);
if (type.equals("ABC_Admission")) {
// do one thing
else {
// do something else
}
} catch (IOException iox) {
DataExtractor.LOG.error("Error extracting data", iox);
this.collector.fail(input);
}