java.io.EOFException: End of input at line 1 column 1 in retrofit 2.0 - web-services

I don't know where is problem
{
"success": "1",
"wallpapers": [
{
"id": "1",
"image": "http://cyphersol.com/apps/ringtona/uploads/gallery/1477685052.jpg"
},
{
"id": "2",
"image": "http://cyphersol.com/apps/ringtona/uploads/gallery/14776850521.jpg"
},
{
"id": "3",
"image": "http://cyphersol.com/apps/ringtona/uploads/gallery/14776850522.jpg"
},
{
"id": "4",
"image": "http://cyphersol.com/apps/ringtona/uploads/gallery/14776850523.jpg"
},
{
"id": "5",
"image": "http://cyphersol.com/apps/ringtona/uploads/gallery/14776850524.jpg"
}
]
}
I am using retrofit2.0
interface
public interface ApiInterface {
#POST("getImages")
Call<WallPaperResponse> getWallpapers(#Query("id") int apiKey);
}
Api Client
public class ApiClient {
public static final String BASE_URL = "http://cyphersol.com/apps/ringtona/webservice/";
private static Retrofit retrofit = null;
public static Retrofit getClient() {
if (retrofit==null) {
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}
Call in to MainActivity
ApiInterface apiService =
ApiClient.getClient().create(ApiInterface.class);
Call<WallPaperResponse> call = apiService.getWallpapers(1);
call.enqueue(new Callback<WallPaperResponse>() {
#Override
public void onResponse(Call<WallPaperResponse> call, Response<WallPaperResponse> response) {
int statusCode = response.code();
List<WallpapersItem> wallpaper = response.body().getWallpapers();
for (int i = 0; i < wallpaper.size(); i++) {
Log.e(TAG, wallpaper.get(i).getImage());
}
// recyclerView.setAdapter(new MoviesAdapter(movies, R.layout.list_item_movie, getApplicationContext()));
}
#Override
public void onFailure(Call<WallPaperResponse> call, Throwable t) {
// Log error here since request failed
Log.e(TAG, t.toString());
}
});
dependency
// retrofit, gson
compile 'com.google.code.gson:gson:2.6.2'
compile 'com.squareup.retrofit2:retrofit:2.0.2'
compile 'com.squareup.retrofit2:converter-gson:2.0.2'

I think This will help you.
KingController mWebController = KingController.getInstance(this);
String apiToken = "1"; mWebController.getMainCategories(apiToken);
#GET("getImages")
Call getWallpaperLis(#Header("id") String api_token);
Regargs
Rashid Ali

Your web service requires id to be sent as a HEADER
While you have rather sent it as a POST parameter.
Hence, Your web service did not return a valid response
and the error.
Let me know if this works.
public interface ApiInterface {
#GET("getImages")
Call<WallPaperResponse> getWallpapers(#Header("id") int apiKey);
}
P.S This site has solid documentation on retorfit
https://futurestud.io/tutorials/retrofit-2-manage-request-headers-in-okhttp-interceptor

Related

Halt the workflow and return the response to Controller

Create Order triggers the Rest End point and starts the workflow (Its a TASK ). CreateOrderController
Problem is CreateOrderController is always returning Success.I want to return ResponseEntity.ok("Not Success "); as shown in 2nd image and stop the call of Save Order Database
How to achieve it?
> #RestController
> public class CreateOrderController {
>
> #Autowired
> private RuntimeService runtimeService;
>
>
>
> #PostMapping("/rest/create/order")
> public ResponseEntity<?> createOrder(#RequestBody OrderInfo orderInfo) {
> Map<String, Object> inputData = new HashMap<String, Object>();
> inputData.put("orderInfo", orderInfo);
> ProcessInstance p = runtimeService.startProcessInstanceByKey("hello-world-process",inputData);
>
>
>
> return ResponseEntity.ok("Success");
>
> }
If you are executing the complete process in one transaction, then an exception along the way will create a rollback. However, you usually have a transaction boundary somewhere. You can query the status of the process instance after it has been started via the history endpoint.
The execute method returns void. Let the delegate write process data instead of returning a value. You can find a setVariable method on the delegateExecution you are getting in as a parameter.
You can get the data values in the REST response as shown in this example: https://docs.camunda.org/manual/7.18/reference/rest/process-definition/post-start-process-instance/#starting-a-process-instance-with-variables-in-return
Request:
{
"variables":{
"aVariable" : {
"value" : "aStringValue",
"type": "String"},
"anotherVariable" : {
"value" : true,
"type": "Boolean",
"valueInfo" : {
"transient" : true
}
}
},
"businessKey" : "myBusinessKey",
"withVariablesInReturn": true
}
Response
{
"links": [
{
"method": "GET",
"href": "http://localhost:8080/rest-test/process-instance/aProcInstId",
"rel": "self"
}
],
"id": "aProcInstId",
"definitionId": "aProcessDefinitionId",
"businessKey": "myBusinessKey",
"ended": false,
"suspended": false,
"tenantId": null,
"variables": {
"anotherVariable": {
"type": "Boolean",
"value": true,
"valueInfo": {
"transient" : true
}
},
"aVariable": {
"type": "String",
"value": "aStringValue",
"valueInfo": { }
}
}
}
Alternatively, error handling options in the delegate code / process include:
a) Simply throw an exception in your execute() method, for instance a new RuntimeException() and observe in Cockpit how Camunda creates a technical incident for the process (https://docs.camunda.org/manual/7.18/webapps/cockpit/bpmn/failed-jobs/).
b) You can also use custom exceptions and error codes, e.g. as shown here:
// Defining a custom exception.
public class MyException extends ProcessEngineException {
public MyException(String message, int code) {
super(message, code);
}
}
// Delegation code that throws MyException with a custom error code.
public class MyJavaDelegate implements JavaDelegate {
#Override
public void execute(DelegateExecution execution) {
String myErrorMessage = "My error message.";
int myErrorCode = 22_222;
throw new MyException(myErrorMessage, myErrorCode);
}
}
Src: https://docs.camunda.org/manual/7.18/user-guide/process-engine/delegation-code/#exception-codes
c) If you don't want to create e technical incident but prefer to throw a 'business' error which you can catch in the process model, so the process can take a different (error) path:
public class BookOutGoodsDelegate implements JavaDelegate {
public void execute(DelegateExecution execution) throws Exception {
try {
...
} catch (NotOnStockException ex) {
throw new BpmnError("Business issue");
}
}
}
src: https://docs.camunda.org/manual/7.18/user-guide/process-engine/delegation-code/#throw-bpmn-errors-from-delegation-code

Geth private network return error "invalid opcode: SELFBALANCE" when executing a simple contract

I setup a simple Geth (v1.10.2-stable-97d11b01) private network (genesis.json config below). I compiled and deployed this simple test contract (solidity version: 0.8.4+commit.c7e474f2.Emscripten.clang):
// SPDX-License-Identifier: UNLICENSED;
pragma solidity >=0.8;
contract CoinA {
bytes32 public coinName = "FAKE";
mapping (address => uint) public balances;
function transfer(address receiver, uint amount) public {
require(balances[msg.sender] >= amount, "Not enough amount");
balances[msg.sender] -= amount;
balances[receiver] += amount;
}
function set(uint amount) public {
require(amount >= 0);
balances[msg.sender] = amount;
}
function get() view public returns (uint) {
return balances[msg.sender];
}
}
However, upon invoking the set method, I received this error:
UnhandledPromiseRejectionWarning: Error: Returned error: invalid opcode: SELFBALANCE
Please advice on how to fix this. Is it because the server doesn't have latest feature that support that opcode? Is there anyway I can compile the code without using that opcode?
I invoked it using Web3JS on Node if it's relevant:
async function setCoin() {
const contract = new w3.eth.Contract(abi, coinAddr);
const query = contract.methods.set(1000);
const tx: TransactionConfig = {
data: query.encodeABI(),
from: accPublicKey,
};
const gas = await w3.eth.estimateGas(tx);
console.log("Estimate Gas: " + gas);
tx.gas = gas;
const signedTx = await w3.eth.accounts.signTransaction(tx, accPrivateKey);
const result = await w3.eth.sendSignedTransaction(signedTx.rawTransaction);
console.log("Done. Gas used: " + result.gasUsed);
}
genesis.json config:
{
"config": {
"chainId": 5777,
"homesteadBlock": 0,
"eip150Block": 0,
"eip155Block": 0,
"eip158Block": 0,
"byzantiumBlock": 0,
"constantinopleBlock": 0,
"petersburgBlock": 0,
"clique": {
"period": 15,
"epoch": 30000
}
},
"difficulty": "1",
"gasLimit": "10000000",
"extradata": "0x00000000000000000000000000000000000000000000000000000000000000001ac7d6c5ecdd24067221a44ee839ba0b847058a30000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
"alloc": {
"1ac7d6c5ecdd24067221a44ee839ba0b847058a3": { "balance": "300000000000000000000000" },
"485012dCc48219dbE955C39e1cee4b71F041d178": { "balance": "300000000000000000000000" },
"ea673022022Ea39a635C7336c6deA8BFa97778D9": { "balance": "300000000000000000000000" }
}
}
The selfbalance opcode was implemented in the Istanbul chain fork (source).
You need to allow the fork in your genesis.json
{
"config": {
"istanbulBlock": 0,

getting property from webservice

I've trying to getting some from information with a WS ,using get method.
I did managed to get the needed information from one WS,but not from a second one.
string url = "";
url = "http://...";
List<Client> listOfClient = null;
string host = url;
WebRequest req = WebRequest.Create(#host);
try
{
HttpWebResponse resp = req.GetResponse() as HttpWebResponse;
if (resp.StatusCode == HttpStatusCode.OK)
{
using (var reader = new StreamReader(resp.GetResponseStream()))
{
JavaScriptSerializer js = new JavaScriptSerializer();
var objText = reader.ReadToEnd();
listOfClient = (List<Client>)js.Deserialize(objText, typeof(List<Client>));
}
}
name = listOfClient.FirstOrDefault().name;
return name;
}
catch (Exception)
{
throw;
}
Here is the Json :
[
{
"city": NY,
"age": 30,
"Name": "Robert",
}
]
I need to read the property offer using the same logic.
{
"contract": "480788888",
"numbers": [
{
"type": "IDEI",
"value": "5987699118"
}
],
"status": "Valid",
"offer": "PNE",
}
Using Newtonsoft.Json.Linq
dynamic obj= JObject.Parse("{ 'contract': '480788888', 'numbers': [ { 'type':
'IDEI', 'value': '5987699118' } ],'status': 'Valid', 'offer': 'PNE', }");
string offer = obj.offer;

Why CXF rest web service returns object if only one object in ArrayList?

When a list has only one object, CXF rest web service return the object instead JSON array. Its working fine for more than one object. Could you please help me to solve this.
For two objects in list JSON response is
{
"list": [
{
"#xsi.type": "interaction",
"interactionId": 92009,
"interactionTitle": "How are you? How is going?",
"interactionType": "Question"
},
{
"#xsi.type": "interaction",
"interactionId": 92004,
"interactionTitle": "This is not working",
"interactionType": "Complaint"
}
],
"message": "Request successfully processed",
"totalRecords": 5,
"statusCode": 2000
}
For one record in list JSON response is
{
"list": {
"#xsi.type": "interaction",
"interactionId": 92009,
"interactionTitle": "How are you? How is going?",
"interactionType": "Question"
},
"message": "Request successfully processed",
"totalRecords": 5,
"statusCode": 2000
}
I am expecting JSON array in both cases. But its returning JSON object instead on JSON Array for single object.
Here I am using Apache CXF rest framework to expose web services.
Here is server side code sample
#GET
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
#Path("/interactions")
public VerveResponse<Interaction> getUserInteractions(){
VerveResponse<Interaction> verveResponse = new VerveResponse<Interaction>();
verveResponse.setStatusCode(""+StatusCode.PROCESSED_SUCCESSFULLY);
verveResponse.setMessage("Request successfully processed");
List<Interaction> interactionList = ExternalService.getInteractionList();
verveResponse.setList(interactionList);
return verveResponse;
}
#XmlRootElement(name = "response")
#XmlSeeAlso({Interaction.class})
public class VerveResponse<T> implements Serializable{
private String statusCode;
private String message;
private List<T> list;
private Long records;
public String getStatusCode() {
return statusCode;
}
public void setStatusCode(String statusCode) {
this.statusCode = statusCode;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Long getRecords() {
return records;
}
public void setRecords(Long records) {
this.records = records;
}
public List<T> getList() {
return list;
}
public void setList(List<T> list) {
this.list = list;
}
}
#XmlRootElement(name = "interaction")
public class Interaction implements Serializable {
private Long interactionId;
private String interactionTitle;
private String interactionType;
public Long getInteractionId() {
return interactionId;
}
public void setInteractionId(Long interactionId) {
this.interactionId = interactionId;
}
public String getInteractionTitle() {
return interactionTitle;
}
public void setInteractionTitle(String interactionTitle) {
this.interactionTitle = interactionTitle;
}
public String getInteractionType() {
return interactionType;
}
public void setInteractionType(String interactionType) {
this.interactionType = interactionType;
}
}

How to extract JSON Array From json in mulesoft

I am getting xml output then i am converting that xml into json object.the format is given below.
{
"SOAP-ENV:Envelope": {
"#xmlns:SOAP-ENV": "http://schemas.xmlsoap.org/soap/envelope/",
"#xmlns:xsi": "http://www.w3.org/2001/XMLSchema-instance",
"#xmlns:xsd": "http://www.w3.org/2001/XMLSchema",
"SOAP-ENV:Body": {
"rpc:TestExampleResponse": {
"#xmlns:rpc": "http://Test.com/asi/",
"TestMessage": {
"listOfTESTS": {
"#xmlns:xmlns": "http://www.Test.com/xml/TEST",
"TESTS": [{
"id": "1",
"lastSyncDate": "12/16/2015 07:06:38",
"listOfTESTsyncrealtimeChild": null
}, {
"id": "2",
"lastSyncDate": "12/16/2015 07:06:38",
"listOfTESTsyncrealtimeChild": null
}
]
}
}
}
}
}
}
i want to extract Test array from JSON Output in Mulesoft.I dont know how to extract that array in mulesoft.Thanks in advance
You can use Dataweave (Transform Message component in Anypoint Studio)
(Mule EE)
Take a look to the documentation:
https://docs.mulesoft.com/mule-user-guide/v/3.7/using-dataweave-in-studio
Sample script for your input:
%dw 1.0
%input payload application/json
%output application/json
---
TESTS: payload."SOAP-ENV:Envelope"."SOAP-ENV:Body"."rpc:TestExampleResponse".TestMessage.listOfTESTS.TESTS map ((tEST , indexOfTEST) -> {
id: tEST.id,
lastSyncDate: tEST.lastSyncDate,
listOfTESTsyncrealtimeChild: tEST.listOfTESTsyncrealtimeChild
})
Output when using %output application/json:
{
"TESTS": [
{
"id": "1",
"lastSyncDate": "12/16/2015 07:06:38",
"listOfTESTsyncrealtimeChild": null
},
{
"id": "2",
"lastSyncDate": "12/16/2015 07:06:38",
"listOfTESTsyncrealtimeChild": null
}
]
}
Output when using %output application/java:
{TESTS=[{id=1, lastSyncDate=12/16/2015 07:06:38, listOfTESTsyncrealtimeChild=null}, {id=2, lastSyncDate=12/16/2015 07:06:38, listOfTESTsyncrealtimeChild=null}]}
You can write a custom transformer like below. This transformer uses Jackson (com.fasterxml.jackson) dependency.
The transformer returns a list of strings where each string represents an element of your TESTS array.
public class JsonArrayExtractor extends AbstractTransformer {
private final ObjectMapper mapper = new ObjectMapper();
private final String testsNodeJsonPointer = "/SOAP-ENV:Envelope/SOAP-ENV:Body/rpc:TestExampleResponse/TestMessage/listOfTESTS/TESTS";
public JsonArrayExtractor() {
registerSourceType(DataTypeFactory.STRING);
}
#Override
protected Object doTransform(Object src, String enc) throws TransformerException {
String payload = Objects.toString(src);
JsonNode root;
try {
root = mapper.readTree(payload);
} catch (IOException e) {
throw new TransformerException(this, e);
}
List<String> testsList = new ArrayList<>();
JsonNode testsNode = root.at(JsonPointer.valueOf(testsNodeJsonPointer));
if (testsNode instanceof ArrayNode) {
ArrayNode testsArrayNode = (ArrayNode) testsNode;
for (JsonNode test : testsArrayNode) {
testsList.add(test.toString());
}
}
return testsList;
}
}
And you can use the above transformer in your flow as below.
<custom-transformer class="org.ram.JsonArrayExtractor" doc:name="extractTestsArray"/>