How to Modify response Result Body in Interceptor Play framework 2.3.8? - interceptor

 #Override
public Promise<Result> call(Http.Context ctx) throws java.lang.Throwable {
Promise<Result> result = this.delegate.call(ctx);
Http.Response response = ctx.response();
response.setHeader("Access-Control-Allow-Origin", "*");
return result.map(r -> {
play.api.mvc.Result res =  r.toScala();
final int status = r.toScala().header().status();
if(status == 200 || status == 201) {
String responseBody = new String(JavaResultExtractor.getBody(r, 0L));
final Map<String,String> headers =  JavaResultExtractor.getHeaders(r);
ResponseHeader responseHeader = res.header();
return new Result(responseHeader, res.body());
}
return r;
});
}
I would like to modify the body of response on interceptor ?. I can able to get the result body. So that I will modify the response. How to override the existing body response and result as Result.

Did the body content update like this.
 
return result.map(r -> {
      final int status = r.toScala().header().status();
      if(status == 200 || status == 201) {
      // Can change the body content here
      Status s = status(status,new String(JavaResultExtractor.getBody(r, 0L)));
      return s.as(JavaResultExtractor.getHeaders(r).get("Content-Type"));
      }
      return r;
      });

Related

how to use long options in c?

how to use long options via getopt_long:
for example like this:
--wide-option
I have --wide and -w.
And on --wide-option it gives the following error:
"unrecognized option"
int main(int argc, char **argv)
{
    struct option opts[] =
    {
        {"wide", 1, 0, 'w'},
        {
            0, 0, 0, 0
        }
    };
    int option_val = 0;
    int counter = 10;
    int opindex = 0;
    while ((option_val = getopt_long(argc, argv, "w:", opts, &opindex)) != -1)
    {
        switch (option_val)
        {
        case 'w':
            if (optarg != NULL)
                counter = atoi(optarg);
            for (int i = 0; i < counter; i++)
                printf("Hello world\n");
            break;
        default:
            return 0;
        }
    }
    return 0;
}
If you look at the cat source code (here), you can see that --number and --number-nonblank are two different options (-b and -n). (near line 555).
If you want to do the same, you can that way:
#include <getopt.h>
#include <stdio.h>
int main(int argc, char **argv)
{
struct option opts[] =
{
{"wide", 1, 0, 'w'},
{"wide-option", 0, 0, 'o'}, /* declare long opt here */
{
0, 0, 0, 0
}
};
int option_val = 0;
int counter = 10;
int opindex = 0;
while ((option_val = getopt_long(argc, argv, "w:o", opts, &opindex)) != -1) /* the case here (I arbitrary choose 'o') */
{
switch (option_val)
{
case 'w':
if (optarg != NULL)
counter = atoi(optarg);
printf("option --wide %d found!\n", counter);
for (int i = 0; i < counter; i++)
printf("Hello world\n");
break;
case 'o': /* and take the case into account */
printf("option --wide-option found!\n");
break;
default:
return 0;
}
}
return 0;
}

when clang compiling to target wasm, it return error for function declaration

I have tried to generate wasm file from the c program.
clang test.c  --target=wasm32-unknown-unknown-wasm -nostartfiles -nostdlib -Wl,--no-entry -Wl,--export-all -o test.wasm
The content of test.c the file is as follows
extern void __VERIFIER_error(void);
extern void __VERIFIER_assume(int);
void __VERIFIER_assert(int cond) {
  if (!(cond)) {
      ERROR: __VERIFIER_error();
  }
  return;
}
int __VERIFIER_nondet_int();
int test() {
    int x = 1;
    int y = 0;
    while (y < 1000 && __VERIFIER_nondet_int()) {
        x = x + y;
        y = y + 1;
    }
    __VERIFIER_assert(x >= y);
    return 0;
}
Encounter the following error message:
clang test.c  --target=wasm32-unknown-unknown-wasm -nostartfiles -nostdlib -Wl,--no-entry -Wl,--export-all -o test.wasm
wasm-ld: error: /tmp/test-e520f3.o: undefined symbol: __VERIFIER_error
wasm-ld: error: /tmp/test-e520f3.o: undefined symbol: __VERIFIER_nondet_int
clang-10: error: linker command failed with exit code 1 (use -v to see invocation)
I have updated content of the file as follows:
extern "C" void __VERIFIER_error(void);
extern "C" void __VERIFIER_assume(int);
extern "C" void __VERIFIER_assert(int cond) {
  if (!(cond)) {
      ERROR: __VERIFIER_error();
  }
  return;
}
extern "C" int __VERIFIER_nondet_int();
int test() {
    int x = 1;
    int y = 0;
    while (y < 1000 && __VERIFIER_nondet_int()) {
        x = x + y;
        y = y + 1;
    }
    __VERIFIER_assert(x >= y);
    return 0;
}
Encounter the following error message, how to get rid of such errors. Can anyone please guide in this regard.
test/test.c:1:8: error: expected identifier or '('
extern "C" void __VERIFIER_error(void);
       ^
test/test.c:2:8: error: expected identifier or '('
extern "C" void __VERIFIER_assume(int);
       ^
test/test.c:3:8: error: expected identifier or '('
extern "C" void __VERIFIER_assert(int cond) {
       ^
test/test.c:9:8: error: expected identifier or '('
extern "C" int __VERIFIER_nondet_int();
       ^
test/test.c:13:24: warning: implicit declaration of function '__VERIFIER_nondet_int' is invalid in C99 [-Wimplicit-function-declaration]
    while (y < 1000 && __VERIFIER_nondet_int()) {
                       ^
test/test.c:17:5: warning: implicit declaration of function '__VERIFIER_assert' is invalid in C99 [-Wimplicit-function-declaration]
    __VERIFIER_assert(x >= y);
    ^
2 warnings and 4 errors generated.
You have two functions without definitions. You do not link any libraries or other object files. So linker is not finding them and issues the error message.

LUA file reading

I am modding a game script where I can locate something in my minimap by getting the specific x,y coordinates. For that, I made a file that stores those values like this :
LocationName
X position
Y position
So, I came out with that code to read them
for line in file:lines() do
            if string.find(line, Location) then
                var1 = file:read("*line")
                var2= ??????????????
            end
        end
The X position can be easily read using the read("*line"), But how am I supposed to read the Y position that is underneath?
This works fine:
var1 = file:read("*line")
var2 = file:read("*line")

Strtok:I dont know why this program keeps failing

In this program the char *token is initialized with a weird garbage value.I am unable to sort it out. Here's the source code:
#include<iostream>
#include<string.h>
#include<stdlib.h>
void fetch_value(char *string,int pos,char *dest)
{
    char *token;
    int i=0;
    token=strtok(string,",");
    if(pos>1)
    {
        token=strtok(NULL,",");
        while(i<pos-1){
            token=strtok(NULL,",");
            printf("token =%s\n",token);
            i++;
        }
        strcpy(dest,token);
    }
    else
    {
        strcpy(dest,token);
    }
}
int main(void)
{
    char checking[100];
    memset(checking,0x00,sizeof(checking));
    fetch_value("14174000100,35679700322,35679700322,35679700322,
            35679700322,14174000999,919440710210000,1",0,checking);
    printf("checking=%s\n",checking);
    return 0;
}
Your help, feedback or suggestions is greatly appreciated.
The first argument of strtok must be modifiable. Your code passes a string literal, which is not modifiable. This leads to undefined behavior.
The simplest modification that will fix the problem is as follows:
char numList[] = "14174000100,35679700322,35679700322,35679700322,35679700322,14174000999,919440710210000,1";
fetch_value(numList, 0, checking);
You should also note that strtok is an older function which is not reentrant, because it uses static variables to save its state. In the new code you should use the reentrant version of the function - strtok_r, which requires you to pass memory for saving the state.
Do this instead:
int main(void)
{
char checking[100];
memset(checking,0x00,sizeof(checking));
char string[] = "14174000100,35679700322,35679700322,35679700322,
35679700322,14174000999,919440710210000,1";
//now string can be modified.
fetch_value(&string[0],0,checking);
printf("checking=%s\n",checking);
return 0;
}

rearranging an array of data without using temporary array

How can I rearrange an array if I know where to put each element in array without using temporary array?
I guess, This has something to do with cyclic permutation but I cannot figure out how they can be linked each other. Wiki page seems irrelevant to me(http://en.wikipedia.org/wiki/Cyclic_permutation)
If you know both where to put each element in the array, and also which element of the array belongs at a specific index, then you can use that information to optimise your rearrangement. Otherwise you can iterate over all the array elements exchanging them into the correct location until they are all correctly placed.
void permuteObjects(Object[] elements, int[] positions)
{
for (int i = 0; i < elements.length; ++i) {
while (positions[i] != i) {
swapObjects(elements, i, positions[i]);
swapIntegers(positions, i, positions[i]);
}
}
}
If you can boil down the "re-arrangement" of your array to single permutations, i.e. to swapping the values of two elements then you can use the XOR to perform the swap without additional variable.
Here a sample code from the linked Wikipedia article:
void xorSwap (int *x, int *y) {
if (x != y) {
*x ^= *y;
*y ^= *x;
*x ^= *y;
}
}
Why not just use a temporary array and terminate it by setting it to null?
Maybe take a look at http://docs.oracle.com/javase/1.4.2/docs/api/java/util/HashMap.html
HashMaps dynamicly increase when adding new items.
Use like this:
HashMap<Integer, WhatEverYouWantToStore> = new HashMap<Integer, WhatEverYouWantToStore>();
Maybe try this:
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
public class sort {
        public static void main(String[] args) {
                List list = new ArrayList();
                String country[] = { "India", "Japan", "USA", "UK", "Nepal" };
                for (int i = 0; i < 5; i++) {
                        list.add(country[i]);
                }
                Collections.sort(list);
                Iterator i = list.iterator();
                while (i.hasNext()) {
                        System.out.print(i.next() + "\t");
                }
        }
}

Resources