User object cannot be resolved to a variable - java

Am novice. Just wrote down a function for login that returns User object but am getting error in last line return oUser as "oUser cannot be resolved to a variable". Can someone please help me in it.I am using User as the return type for sLoginContractTest function.
public User sLoginContractTest(String sUserName, String sPassword, String sDomain,
String sBusUnitID) throws Exception {
String[] sInfo = new String[2];
Gson gson = new GsonBuilder().create();
// Create your http client
CloseableHttpClient httpclient = HttpClientBuilder.create().build();
// Create http post object
// HttpPost postRequest = new HttpPost(sUrl);
HttpPut putRequest = new HttpPut(this.sAuthUrl);
// Message Body
StringEntity input = new StringEntity("{\"userId\":\"" + sUserName
+ "\",\"password\":\"" + sPassword + "\",\"businessUnitId\":\""
+ sBusUnitID + "\",\"domainName\":\"" + sDomain + "\"}");
// Set content type for post
input.setContentType("application/json");
// attach message body to request
putRequest.setEntity(input);
// submit request and save response
HttpResponse response = httpclient.execute(putRequest);
// get status code from response
int sStatusCode = response.getStatusLine().getStatusCode();
// Check if status code returned is 200 (success) or other (failure)
if (sStatusCode != 200) {
ReportResults("FAIL", "Login Failed due to " + response.toString(),
false);
Assert.fail(response.getStatusLine().getReasonPhrase());
sInfo = null;
}
// Expected response
else if (sStatusCode == 200) {
System.out.println(response.toString());
ReportResults("PASS", "Logged in Successfully.", false);
// Get response body (entity and parse to string
String sEntity = EntityUtils.toString(response.getEntity());
User oUser = gson.fromJson(sEntity, User.class);
// Get securityID and token
sInfo[0] = this.getJsonResponseValue(sEntity, "securityId");
sInfo[1] = this.getJsonResponseValue(sEntity, "token");
//Check to see if Contract is valid
try{
if(oUser!=null){
return oUser;
}
else{
return null;
}
}
catch(Exception e){
//If exception, contract failed (might want to check for specific exception here)
ReportResults("FAIL", "Login user contract failed because: " + e.getMessage(),false);
}
this.setUserID(sUserName);
this.sAuthToken = sInfo;
System.out.println("the security id is" + this.sAuthToken[0]);
System.out.println("the token id is " + this.sAuthToken[1]);
}
return oUser;
}

Related

i was given task to fix sonar issues and generate report, then there is an error "Use a more secure method than basic authentication", couldn't get it

would appreciate any help to fix it with some detailed explanation , one of the solution saying to use Digest authentication, if it's correct, how do we use in the below code, the error pointed to "httppost.setHeader("Authorization", "Basic " + encoding);" this line
try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
String encoding;
LOGGER.info("Entered into try");
if (direction != null && direction.equalsIgnoreCase(ASPERA_DIRECTION_DOWNLOAD)) {
LOGGER.info("entered if");
url = acceleratorUtilConfig.getAccelDownloadSetupUrl();
path = acceleratorUtilConfig.getS3DownloadRootPath() + path;
encoding = new String(Base64.encodeBase64((acceleratorUtilConfig.getAccelDownloadAccessKey() + ":" + acceleratorUtilConfig.getAccelDownloadSecret()).getBytes()));
} else {
LOGGER.info("entered else");
url = acceleratorUtilConfig.getAccelUploadSetupUrl();
path = acceleratorUtilConfig.getS3UploadRootPath() + path;
encoding = new String(Base64.encodeBase64((acceleratorUtilConfig.getAccelUploadAccessKey() + ":" + acceleratorUtilConfig.getAccelUploadSecret()).getBytes()));
}
LOGGER.debug("GenerateToken : {} : {}", url, path);
LOGGER.debug(": {}", encoding);
LOGGER.debug(" : {} : {}", direction, filePathArray);
LOGGER.debug("NewGenerateToken : {}", acceleratorUtilConfig.getAccelDownloadSetupUrl());
TokenRequest tokreq = new TokenRequest(
Stream.of(new TransferRequest(new TransferRequestAttribute(true, "always", direction, path,
pathModel.getPathList(filePathArray), null), null)).collect(Collectors.toList()),
null);
ObjectMapper mapper = new ObjectMapper();
String inJson = "";
inJson = mapper.writeValueAsString(tokreq);
HttpPost httppost = new HttpPost(url);
httppost.setHeader("Authorization", "Basic " + encoding);
StringEntity input = new StringEntity(inJson);
httppost.setEntity(input);
LOGGER.debug("GenerateToken : Request sent");
HttpResponse response1 = httpClient.execute(httppost);
LOGGER.debug("GenerateToken : response returned");

Java - Accessing Secure HTTPS Third Party API

I am editing a Java application and trying to access a secure third party API. There are two String variables that need to be passed, and ID and a token for the secure access. The code below is using Maven. I am trying to tweak the code for just Java.
public class JavaApiStreaming {
public static void main (String[]args) throws IOException {
HttpClient httpClient = HttpClientBuilder.create().build();
try {
// Set these variables to whatever personal ones are preferred
String domain = "https://stream-fxpractice.oanda.com";// trying to access this api
String access_token = "ACCESS-TOKEN"; //using this token
String account_id = "1234567"; //using this ID
String instruments = "EUR_USD,USD_JPY,EUR_JPY";
// This is the part of the code I am trying to edi. to my knowledge this is //maven coding
HttpUriRequest httpGet = new HttpGet(domain + "/v1/prices?accountId=" + account_id + "&instruments=" + instruments);
httpGet.setHeader(new BasicHeader("Authorization", "Bearer " + access_token));
System.out.println("Executing request: " + httpGet.getRequestLine());
HttpResponse resp = httpClient.execute(httpGet);
HttpEntity entity = resp.getEntity();
if (resp.getStatusLine().getStatusCode() == 200 && entity != null) {
InputStream stream = entity.getContent();
String line;
BufferedReader br = new BufferedReader(new InputStreamReader(stream));
while ((line = br.readLine()) != null) {
Object obj = JSONValue.parse(line);
JSONObject tick = (JSONObject) obj;
// unwrap if necessary
if (tick.containsKey("tick")) {
tick = (JSONObject) tick.get("tick");
}
// ignore heartbeats
if (tick.containsKey("instrument")) {
System.out.println("-------");
String instrument = tick.get("instrument").toString();
String time = tick.get("time").toString();
double bid = Double.parseDouble(tick.get("bid").toString());
double ask = Double.parseDouble(tick.get("ask").toString());
System.out.println(instrument);
System.out.println(time);
System.out.println(bid);
System.out.println(ask);
}
}
} else {
// print error message
String responseString = EntityUtils.toString(entity, "UTF-8");
System.out.println(responseString);
}
} finally {
httpClient.getConnectionManager().shutdown();
}
}
}
It seems like you're asking how to use the standard library instead of any dependencies and encode the account_id/access token as part of basic auth header. I would suggest using HttpURLConnection. It's included as part of the Java standard library. Try the following:
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
String encoded = Base64.encode(account_id+":"+access_token);
connection.setRequestProperty("Authorization", "Basic "+encoded);

Can't get OkHttp's response.body.toString() to return a string

I'm trying to get some json data using OkHttp and can't figure out why when i try logging the response.body().toString() what i get is Results:﹕ com.squareup.okhttp.Call$RealResponseBody#41c16aa8
try {
URL url = new URL(BaseUrl);
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(url)
.header(/****/)
.build();
Call call = client.newCall(request);
Response response = call.execute();
**//for some reason this successfully prints out the response**
System.out.println("YEAH: " + response.body().string());
if(!response.isSuccessful()) {
Log.i("Response code", " " + response.code());
}
Log.i("Response code", response.code() + " ");
String results = response.body().toString();
Log.i("OkHTTP Results: ", results);
I don't know what i'm doing wrong here. How do i get the response string?
You have use .string() function to print the response in System.out.println(). But at last in Log.i() you are using .toString().
So please use .string() on response body to print and get your request's response, like:
response.body().string();
NOTE:
.toString(): This returns your object in string format.
.string(): This returns your response.
I think this solve your problem... Right.
Just in case someone bumps into the same weird thing as I have. I run my code during development in Debug Mode and apparently since OKHttp 2.4
..the response body is a one-shot value that may be consumed only once
So when in debug there is a call "behind the scene" from the inspector and the body is always empty. See: https://square.github.io/okhttp/3.x/okhttp/okhttp3/ResponseBody.html
The response.body.string() can be consumed only once.
Please use as below:
String responseBodyString = response.body.string();
Use the responseBodyString as needed in your application.
Given that a response can potentially produce an OutOfMemoryError in cases of large files, you can instead "peek" the body with the number of bytes and call the string() method.
Note that this will consume the body.
response.peekBody(500).string());
Following is my modified CurlInterceptor. Check the end of the intercept function where I m recreating the Response object after consuming the old Response.
var responseBodyString = responseBody?.string()
response = response.newBuilder()
.body(
ResponseBody.create(
responseBody?.contentType(),
responseBodyString.toByteArray()
)
)
.build()
class CurlInterceptor: Interceptor
{
var gson = GsonBuilder().setPrettyPrinting().create()
override fun intercept(chain: Interceptor.Chain): Response {
Timber.d(" **** ->>Request to server -> ****")
val request = chain.request()
var response = chain.proceed(request)
var curl = "curl -v -X ${request.method()}"
val headers = request.headers()
for ( i in 0..(headers.size() -1) ){
curl = "${curl} -H \"${headers.name(i)}: ${headers.value(i)}\""
}
val requestBody = request.body()
if (requestBody != null) {
val buffer = Buffer()
requestBody.writeTo(buffer)
var charset: Charset =
Charset.forName("UTF-8")
curl = "${curl} --data '${buffer.readString(charset).replace("\n", "\\n")}'"
}
Timber.d("$curl ${request.url()}")
Timber.d("response status code ${response.code()} message: ${response.message()}")
dumbHeaders(response)
var responseBody = response?.body()
if(responseBody != null )
{
var responseBodyString = responseBody?.string()
response = response.newBuilder()
.body(
ResponseBody.create(
responseBody?.contentType(),
responseBodyString.toByteArray()
)
)
.build()
responseBodyString = gson.toJson(responseBodyString)
Timber.d("response json -> \n $responseBodyString")
}
Timber.d(" **** << Response from server ****")
return response
}
fun dumbHeaders(response: Response) {
try {
if (response.headers() != null) {
for (headerName in response.headers().names()) {
for (headerValue in response.headers(headerName)) {
Timber.d("Header $headerName : $headerValue")
}
}
}
}
catch (ex: Exception){}
}
}
Instead of using .toString() which returns an object
String results = response.body().toString();
you can use
String results = response.body().string();
Call call = client.newCall(request);
return call.execute().body().string();
we can get response as a return fromby these
try to change it like that for example:
protected String doInBackground(String... params) {
try {
JSONObject root = new JSONObject();
JSONObject data = new JSONObject();
data.put("type", type);
data.put("message", message);
data.put("title", title);
data.put("image_url", imageUrl);
data.put("uid",uid);
data.put("id", id);
data.put("message_id", messageId);
data.put("display_name", displayName);
root.put("data", data);
root.put("registration_ids", new JSONArray(receipts));
RequestBody body = RequestBody.create(JSON, root.toString());
Request request = new Request.Builder()
.url(URL)
.post(body)
.addHeader("Authorization", "key=" + serverKey)
.build();
Response response = mClient.newCall(request).execute();
String result = response.body().string();
Log.d(TAG, "Result: " + result);
return result;
} catch (Exception ex) {
Log.e(TAG,"Exception -> "+ex.getMessage());
}
return null;
}
Recreate the response object after consuming the string
val responseBodyString = response.body()!!.string()
response = response.newBuilder()
.body(ResponseBody.create(responseBody?.contentType(), responseBodyString.toByteArray()))
.build()
Kotlin Programmers I am here for you
response.body?.charStream()?.readText()?.let {
//Where it refers to Response string
callBack.onAPISuccess(it)
}
Here you can not use .toString() function and .string() function is not available in Kotlin than you can user charStream() and than convert that charStream into readText() but you have to unwrap the whole value before passing it.But it will never create problem.
I have not explored these charStream() and readText() functions in java but I think it should be there and you can use this in java if these functions are available because I just got to know that java has deprecated the .string() function.

HttpRequestBase - How to print the request with all its data

I'm using HttpRequestBase and I want to log the request fully to a log file before using it.
The default toString returns only the request line and I want to print all the headers, parameters, request body etc...
Is there a way to do so?
The HttpRequestBase object (HttpGet, HttpPost, etc.) contains information about the headers, parameters, and the implementation class contains the body, but it's not actually serialized into a String. That happens when the HttpClient actually sends the request.
You can play with the http components logging configuration.
Or you can call the appropriate methods and do it yourself.
HttpRequestBase base = new HttpGet("www.google.com");
Header[] headers = base.getAllHeaders();
// iterate and print
For the body, you need to cast to your implementation class and get the HttpEntity, if it has one.
HttpEntity entity = ((HttpPost)base).getEntity(); // example
And print it (its InputStream content). Note: That might consume the entity.
Full example
HttpPost post = new HttpPost("www.google.com");
post.setHeader(new BasicHeader("User-Agent", "random client"));
HttpEntity entity = new StringEntity("yellaworld");
post.setEntity(entity);
Header[] headers = post.getAllHeaders();
String content = EntityUtils.toString(entity);
System.out.println(post.toString());
for (Header header : headers) {
System.out.println(header.getName() + ": " + header.getValue());
}
System.out.println();
System.out.println(content);
prints
POST www.google.com HTTP/1.1
User-Agent: random client
yellaworld
This works
private void printRequest() {
System.out.println("receive " + httpRequest.getMethod() +" notification for "+ httpRequest.getRequestURI());
System.out.println(" \n\n Headers");
Enumeration headerNames = httpRequest.getHeaderNames();
while(headerNames.hasMoreElements()) {
String headerName = (String)headerNames.nextElement();
System.out.println(headerName + " = " + httpRequest.getHeader(headerName));
}
System.out.println("\n\nParameters");
Enumeration params = httpRequest.getParameterNames();
while(params.hasMoreElements()){
String paramName = (String)params.nextElement();
System.out.println(paramName + " = " + httpRequest.getParameter(paramName));
}
System.out.println("\n\n Row data");
System.out.println(extractPostRequestBody(httpRequest));
}
static String extractPostRequestBody(HttpServletRequest request) {
if ("POST".equalsIgnoreCase(request.getMethod())) {
Scanner s = null;
try {
s = new Scanner(request.getInputStream(), "UTF-8").useDelimiter("\\A");
} catch (IOException e) {
e.printStackTrace();
}
return s.hasNext() ? s.next() : "";
}
return "";
}

process in-app apple receipt with java

I am using a java backend. After a user performs an in-app purchase, the front-end sends me the receipt. In turn, I am to send the receipt to apple for confirmation; then apple is to decode the receipt and send me back a JSON dictionary. My question is about sending the receipt back to apple so that I may get the json response. I am using the code below. But I keep getting {"status":21002} from apple and something about "Invalid cookie header". Any ideas how to solve this?
String url = "https://buy.itunes.apple.com/verifyReceipt";
DefaultHttpClient client = null;
try {
String input = IOUtils.toString(is);
log.info("THE INPUTSTREAM: " + input);
JSONObject receipt = new JSONObject();
receipt.put("receipt-data", input);
client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
StringEntity entity = new StringEntity(receipt.toString());
entity.setContentType("application/json");
post.setEntity(entity);
HttpClientParams.setRedirecting(post.getParams(), false);
HttpResponse response = client.execute(post);
if (300 <= response.getStatusLine().getStatusCode()) {
throw new RuntimeException("No response from iTune store. status code: " + response.getStatusLine().getStatusCode());
}
if (null == response.getEntity()) {
log.info("Response is null");
throw new Exception("Response is null");
}
StringBuilder sb = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
for (String line; null != (line = reader.readLine());) {
sb.append(line);
}
JSONObject json = new JSONObject(sb.toString());
log.info("THE JSON" + json);
//Then work with json below
} catch (Exception e) {
throw new WebApplicationException(Response.status(Status.BAD_REQUEST).entity(e.getMessage()).build());
} finally {
if (null != client) {
client.getConnectionManager().shutdown();
}
}
No need cookie I think? try
HttpClientParams.setCookiePolicy(client.getParams(), CookiePolicy.IGNORE_COOKIES);

Categories

Resources