Server Data is not Coming: Angular2 - java

I have created a simple app using REST in java which return string value successfully with REST client. Now I want to get string value using Http rest client in Angular2. I have created service for getting data from rest client in angular2 which saying successfully access rest but when I am printing data like {{serverData}} it's print nothing.
service.ts
#Injectable()
export class HttpSiftgridService {
private url:string = "http://localhost:8080/app-rest/rest /get/getData";
constructor(private _http: Http) {}
getSiftgridData() {
alert(this._http.get(this.url).map(res => res.json));
alert("hh");
return this._http.get(this.url).map(res => res.json);
}
private handleError(error : Response) {
console.error(error);
return Observable.throw(error.json().error || ' error');
}
}
app.component.ts
export class AppComponent implements OnInit{
serverData: string;
constructor(private _httpService:HttpSiftgridService) {}
ngOnInit() {
this._httpService.getSiftgridData()
.subscribe(
data => this.serverData = JSON.stringify(data),
error => console.log("Error in getting Data"),
() => console.log("Successfully")
);
}
}
my rest app running on tomcat.

Change:
return this._http.get(this.url).map(res => res.json);
To:
return this._http.get(this.url).map(res => res.json());

I know it's not a real answer but that wouldn't work as comment:
If you change it to
ngOnInit() {
this._httpService.getSiftgridData()
.subscribe(
data => {
this.serverData = JSON.stringify(data);
console.log(data);
},
error => console.log("Error in getting Data"),
() => console.log("Successfully")
);
}
is the data printed?
Is Successfully printed?

Related

angular, Java : HTTP request not going to server, while URL is valid

I am working in an application : Java Backend and Angular frontend. I am using angular Fromly, data is coming to service, but from the service it is not going to server.
lets share the code snipts:
Service Code:
export class RecommendationRequestService {
readonly ROOT_URL = environment.apiUrl + '/am/v1/recommendation-requests';
constructor(private http: HttpClient, private configService: RecommenderConfigService) {
} ​
​
​updateData(interviewStatus: InterviewStatusRecommendation): Observable<any> {
​console.log(interviewStatus);
​return this.http.put<any>(this.ROOT_URL, interviewStatus);
​}
​}
This line is printing intended data set : console.log(interviewStatus);
The server is running.
The code from where the service is being called :
onSubmit() {
this.model.recommendationRequest.agentInitiationId = this.agentInitiationId;
const subs = this.service.updateData(this.model).subscribe(response => {
console.log('------' + response);
if (response === 'OK') {
this.notify.success('Request Recommendation Update success.');
} else {
this.notify.error('Request Recommendation Update fail.');
}
},
err => {
if (err.error.hasOwnProperty('code') && err.error.code === 1000) {
this.notify.error(CommonEnum.VALIDATION_ERROR);
}
});
subs.unsubscribe();
}
console.log('------' + response); this line should print at least -----, But nothing.
I have checked the network monitor from the browser, no call is going.
What might be the possible issue, any thing from fromly?
You are doing it incorrect as Aldin Bradaric also updated in the comment, as soon as you make the call on the very next moment you are unsubscribing it. This is what you should do :
public subs: [] = [];
onSubmit() {
this.model.recommendationRequest.agentInitiationId = this.agentInitiationId;
const subs = this.service.updateData(this.model).subscribe(response => {
console.log('------' + response);
if (response === 'OK') {
this.notify.success('Request Recommendation Update success.');
} else {
this.notify.error('Request Recommendation Update fail.');
}
},
err => {
if (err.error.hasOwnProperty('code') && err.error.code === 1000) {
this.notify.error(CommonEnum.VALIDATION_ERROR);
}
});
//subs.unsubscribe(); // remove it and add it to the lifecycle hooks
this.subs.push(subs);
}
ngOnDestroy() {
// create an array of subscription
this.subs.forEach(sub => sub.unsubscribe() )
}

Error 500 when use axios call service on Linux enviroment but working on local on Windows

I use react for frontend and Java for Backend.
When i call service on local. It'work but error 500 on test enviroment(linux)
React (Frontend) :
const getDatas = async () => {
const config = {
method: 'get',
url: process.env.REACT_APP_API_URL + 'get-all-to-acc-transaction',
withCredentials: true,
params: {
type: '01',
objectType: null,
},
}
const result = await axios(config);
if (result.data.code == '00') {
//todo somethings
}
}
Java (Backend)
#GetMapping("/get-all-acc-transaction-combobox")
public ResponseEntity<Object> getAllAccTransactionCombobox(#RequestParam String type) {
return txnManualService.getAllAccTransactionCombobox(type);
}
Url API local:
http://localhost:2998/project-test/get-all-acc-transaction-combobox?type=1
Url API test environment:
http://10.23.8.187:2998/project-test/get-all-acc-transaction-combobox?type=1
When change url test enviroment to:
http://10.23.8.187:2998/project-test/get-all-acc-transaction-combobox?type='1'. It work.
So where did I go wrong? I think the backend is still receiving the parameter type is string and the axios passing is numeric so the error. Thanks everyone :(((

Problem with authenticating private channels in laravel with java client

I want to send broadcast messages from server (using laravel) to clients (using java).
What I'm using
Pusher as boradcast driver.
laravel passport for api authentication.
What I've done in server side
I've configured my Pusher credentials in .env file.
Uncommented App\Providers\BroadcastServiceProvider::class line in config/app.php file.
In config/auth.php file I've added the following:
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'devices' => [
'driver' => 'session',
'provider' => 'devices',
],
'api' => [
'driver' => 'passport',
'provider' => 'devices',
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\User::class,
],
// using devices table to authenticate over api guard
'devices' => [
'driver' => 'eloquent',
'model' => App\Device::class,
],
],
In App\Providers\BroadcastServiceProvider class I added the following to boot() function:
Broadcast::routes(['prefix' => 'api', 'middleware' => 'auth:api']);
In routes/channels.php I added the following:
Broadcast::channel('device.{device_id}', function ($device, $device_id) {
return $device->id === $device_id;
});
Created an event AdvertisementAdded by running php artisan make:event AdvertisementAdded, added implements ShouldBroadcast then added the following to its broadcastOn() method:
return new PrivateChannel('device.'.$this->device_id);
What I've done in client side
Because I'm just testing now, I got my access_token and device_id by sending a login request from postman
I copied that accessToken to my java client and stored it in accessToken variable as String, here's the code:
String accessToken = "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImp0aSI6ImY3ZTVlMTAzZWE3MzJjMTI5NzY1YTliMmMzOTM0N2ZhOGE4OTU5MjRjNDA5ZjgyOTA4ZDg5NTFjZTBkOGZlNTA2M2M1YTI1MDBlOTdhZDdiIn0.eyJhdWQiOiIxIiwianRpIjoiZjdlNWUxMDNlYTczMmMxMjk3NjVhOWIyYzM5MzQ3ZmE4YTg5NTkyNGM0MDlmODI5MDhkODk1MWNlMGQ4ZmU1MDYzYzVhMjUwMGU5N2FkN2IiLCJpYXQiOjE1NTkwOTYyNDgsIm5iZiI6MTU1OTA5NjI0OCwiZXhwIjoxNTkwNzE4NjQ3LCJzdWIiOiI3Iiwic2NvcGVzIjpbXX0.FKeE9Z-wv2yUNQPl-qsbu9baYGTdbQ6DuzaI1R8azR6l1CIP9uRI4hCaoWvgx0GXWWLPRNhfQl-YD3KP2YOraW16-h4ie_95B9VQrpFxXnlqKojsfh1xSrSNSl5HncslMWQPVjoesBpM5y_cpG19PGgu-SWo0W6s9Fiz_Nm70oyyZB9mSqU8PVQvAOSNr6TMR0aC3iMLFfkyZkTSwj8EoRyD2LGW6v4PFriqx8JLbZASCOiUYBlYnunWrTFDOAenZcoa5Sw7u7kbSvYehjDKRwKjQM6zmPfi0A3Mp0CHjHE599OXb-NG2IMH-wmlT0vEZjP2U97hxmsNW1RtHNXWaRKFL9T-WVmZbJf3fH5hXqTv495L3MQfq_m5YFHyc5NuIqK4K4xMJB956a33ICnH8DmvPmJgderNAhqEX1JHUAsR63K7xbZxRBDS8OlQYcEf-_v75X0kT1s067enSvI8Vs212AVnI6k0FmgQNM8DfJUq6YduD0m2F2ZWpKPrwdd6PdW5ZlZTEv-D8dYIEQ_CwOWohNoENATmTqxDpPBxK5c723MEt8S7Sa9MEGAo56HW3-9pbazbEdY1GqPWKVkov7K_6eBFcWsV67AgJpoKFt6RiBfRvokgiH96WG89qBB_Ucpm8uBahX93FaOXhVLW0VjJH2LQKrGw0bb5LS8Ql5o";
String deviceId = "7";
Map<String, String> authHeaders = new HashMap();
authHeaders.put("Authorization", accessToken);
HttpAuthorizer authorizer = new HttpAuthorizer("http://localhost:8000/api/broadcasting/auth");
authorizer.setHeaders(authHeaders);
PusherOptions options = new PusherOptions();
options.setAuthorizer(authorizer).setCluster(PUSHER_CLUSTER);
Pusher pusher = new Pusher(PUSHER_APP_KEY, options);
pusher.subscribePrivate("private-device." + deviceId, new PrivateChannelEventListener() {
#Override
public void onEvent(String channelName, String eventName, final String data) {
System.out.println(String.format("Received event on channel [%s]", channelName));
}
#Override
public void onSubscriptionSucceeded(String string) {
System.out.println(String.format("Subscribed to channel [%s]", string));
}
#Override
public void onAuthenticationFailure(String string, Exception excptn) {
System.out.println(string);
}
});
pusher.connect(new ConnectionEventListener() {
#Override
public void onConnectionStateChange(ConnectionStateChange change) {
System.out.println("State changed to " + change.getCurrentState() +
" from " + change.getPreviousState());
}
#Override
public void onError(String message, String code, Exception e) {
System.out.println("There was a problem connecting!");
}
});
// Keeping main thread alive
while (true) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
When running the code above, it outputs the following on console:
State changed to CONNECTING from DISCONNECTED
State changed to CONNECTED from CONNECTING
java.io.IOException: Server returned HTTP response code: 403 for URL: http://localhost:8000/api/broadcasting/auth
I'm sure that auth:api middleware is working as I expect on other requests.
Here's a snippet from my routes/api.php:
Route::middleware('auth:api')->group(function () {
Route::prefix('advertisements')->group(function () {
Route::get('/request', 'AdvertisementsController#getDeviceAdvertisements')
->name('advertisements.getDeviceAdvertisements');
});
});
And here's a test to that route from postman (with the same access token as above):
And here's a test to api/broadcasting/auth route from postman (with the same access token as above):
What's the problem? Why all api routes under auth:api middleware working properly but not api/broadcasting/auth route??
Note
I tried working with public channels with no problems.
After a whole day of searching, finally It's solved.
The error happens when authorizing the channel, not when authenticating the request using auth:api middleware.
My private channel authorizing function in routes/channels.php always returns false meaning it will reject all subscribing requests to private-device.{device_id} channel:
Broadcast::channel('device.{device_id}', function ($device, $device_id) {
// this always return false, because of inequality of types
return $device->id === $device_id;
});
Authorizing function above always return false, because of inequality of types between $device->id (which is of type int) and $device_id (which is of type string).
So, in order to solve the problem, I cast both of them to int and then checked for equality.
Here's the code I used to solve the problem:
Broadcast::channel('device.{device_id}', function ($device, $device_id) {
return (int) $device->id === (int) $device_id;
});

React-native-uploader Android Errors

I'm currently trying to debug a react-native package (react-native-uploader) I'm using to try and upload a bundle of files (photos). Despite working on ios, the current implementation is returning the following error for android:
Response{protocol=http/1.1, code=405, message=Method Not Allowed, url=${config.apiBase}/load/${this.props.id}/uploadconfirmation}
The error is originating from this line in the package:
Response response = client.newCall(request).execute();
Where the client is:
private final OkHttpClient client = new OkHttpClient()
Where request is:
Request{method=POST, url=${config.apiBase}/load/${this.props.id}/uploadconfirmation, tag=null}
I've successfully made posts to the endpoint using formdata:
let tData = new FormData();
const that = this;
tData.append("confirmation_doc", {
uri: files[0].filepath,
type: "image/jpeg",
name: "confirmation_doc.jpg",
});
axios.post(
`${config.apiBase}/load/${this.props.id}/uploadconfirmation`,
tData
)
.then(response => {
Alert.alert(
"Success",
"Uploaded Successfully!",
[{ text: "OK", onPress: () => that.props.close() }],
{ cancelable: false }
);
});
I've tried looking through the source code to determine where things are falling apart and it seems like everything is posting as it should (headers look good, method looks good, endpoint looks good). I'm not all too familiar with Java so any input would be appreciated.
HTTP 405 Method Not Allowed ... is a client-side error.
The method received in the request-line is known by the origin server but not supported by the target resource.
if the JavaScript works, but the Java won't... you might be looking for the MultipartBuilder
... in combination with MediaType.FORM.
In order to solve this issue, I had to abandon the react-native-uploader package I had been using. Below is how I managed to resolve the issue:
let tData = new FormData();
this.state.selectedImages.forEach((item, i) => {
tData.append("doc[]", {
uri: item.uri,
type: "image/jpeg",
name: item.filename || `filename${i}.jpg`,
});
});
fetch(`${config.apiBase}/load/${this.props.id}/uploadconfirmation`, {
method: "post",
headers: {
Accept: "application/x-www-form-urlencoded",
Authorization: `Token ${this.props.token}`,
},
body: tData,
})
.then(res => res.json())
.then(res => {
Alert.alert(
"Success",
"Uploaded Successfully!",
[{ text: "OK", onPress: () => that.props.close() }],
{ cancelable: false }
);
})
.catch(err => {
console.error("error uploading images: ", err);
});

Get response text from a JSONP request in Ext / Java Application

I am trying to connect a Java REST service to a ExtJs JSONP request but even though the java method executes I haven't been able to get a response test. This is what I am trying:
Java Code:
#Path("/hello")
public class Hello {
#GET
#Produces("text/javascript") // have also tried application/json
public String sayJsonHello(#QueryParam("_dc") String dcIdentifier, #QueryParam("callback") String callback) {
System.out.println(callback);
callback += "({\"success\":true, \"msj\":" + "\"" + "Exitoooo!" + "\" });";
System.out.println(callback);
return callback;
}
}
ExtJs code:
Ext.data.JsonP.request({
url: "http://10.1.50.66:7001/Simulador/webresources/hello",
params: {
},
callback: function (response) {
console.log(response); //true
console.log(response.result); //undefined
console.log(response.responseText); //undefined
console.log(response.success); // undefined
if (response.success === true) {
Ext.Msg.alert('Link Shortened', response.msj, Ext.emptyFn);
} else { // entering here :( why ?
Ext.Msg.alert('Error', response.msj, Ext.emptyFn);
}
}
});
response is printting true, everything else undefined :(
callback looks like this Ext.data.JsonP.callback1({"success":true, "msj":"exito"})
Any ideas what could be wrong?
Ok this worked out for me:
Ext.data.JsonP.request({
url: "http://10.1.50.66:7001/Simulador/webresources/hello",
callbackKey: 'callback1',
params: {
},
success : function(response) {
console.log("Spiffing, everything worked");
// success property
console.log(response.success);
// result property
console.log(response.result);
console.log(response.msj);
},
failure: function(response) {
console.log(response);
Ext.Msg.alert('Error', 'Please try again.', Ext.emptyFn);
}
});

Categories

Resources