get value by name of a websocket response(string) - java

How to get the value by name of a websocket response(string),I have tried convert response into jsonArray but it didn't work.
So how can I get the value(mop floor) by key(task)? I am using android studio to develop app. The problem occurs at output ("Task to do: " +text.get("task"));
private final class EchoWebsocketListener extends WebSocketListener{
#Override
public void onOpen(WebSocket webSocket, okhttp3.Response response) {
webSocket.send("{\n" +
" \"task\": \"Mop floor\",\n" +
" \"time_limit\": \"1\"\n" +
"}");
}
#Override
public void onMessage(WebSocket webSocket, String text) {
output("Task to do: " +text.get("task"));
}
#Override
public void onClosed(WebSocket webSocket, int code, String reason) {
webSocket.close(1000,"Goodbye!");
}
#Override
public void onFailure(WebSocket webSocket, Throwable t, okhttp3.Response response) {
output("Error in websocket : " + t.getMessage());
}
}

Related

Unable to pull docker image from AWS ECR with docker-java

I have an issue similar to this post : Pulling image from Amazon ECR using docker-java. Although, even by adding the "withAuthConfig" and "withRepository", I still have the "unauthorized: incorrect username or password". Any idea why ?
My code :
public void pullImage() {
GetAuthorizationTokenRequest request = new GetAuthorizationTokenRequest();
// Get Authorization Token
GetAuthorizationTokenResult response = client.getAuthorizationToken(request);
AuthorizationData authData = response.getAuthorizationData().get(0);
String userPassword = StringUtils.newStringUtf8(Base64.decodeBase64(authData.getAuthorizationToken()));
String user = userPassword.substring(0, userPassword.indexOf(":"));
String password = userPassword.substring(userPassword.indexOf(":") + 1);
DockerClientConfig config = DefaultDockerClientConfig.createDefaultConfigBuilder()
.withDockerTlsVerify(false)
.withRegistryUsername(user)
.withRegistryPassword(password)
.withRegistryUrl(authData.getProxyEndpoint().replace("https://", ""))
.build();
DockerHttpClient httpClient = new ApacheDockerHttpClient.Builder()
.dockerHost(config.getDockerHost())
.sslConfig(config.getSSLConfig())
.maxConnections(100)
.connectionTimeout(Duration.ofSeconds(30))
.responseTimeout(Duration.ofSeconds(45))
.build();
//Docker client
DockerClient dockerClient = DockerClientImpl.getInstance(config, httpClient);
// Response
AuthResponse authResponse = dockerClient.authCmd().exec();
System.out.println(authResponse.getStatus());
// Pull image
PullImageCmd pullImageCmd = dockerClient
.pullImageCmd(respositoryname)
.withAuthConfig(dockerClient.authConfig())
.withRepository(respositoryname);
pullImageCmd.exec(new ResultCallback<PullResponseItem>() {
#Override
public void onStart(Closeable closeable) {
System.out.println("Pull started : " + closeable);
}
#Override
public void onNext(PullResponseItem object) {
System.out.println("Pull on next : " + object);
}
#Override
public void onError(Throwable throwable) {
System.out.println("Pull error : " + throwable);
}
#Override
public void onComplete() {
System.out.println("Pull finished");
}
#Override
public void close() throws IOException {
System.out.println("Pull closed");
}
});
}
Result :
Login Succeeded
Pull error : com.github.dockerjava.api.exception.InternalServerErrorException: Status 500: {"message":"Get \"https://registry-1.docker.io/v2/library/pleiade3tierserver/tags/list\": unauthorized: incorrect username or password"}

eventsource-android returns empty data String from Flux server endpoint

I have successfully implemented this github library for SSE Handling in Android.
The problem
Each time i'm sending data to the stream , the onMessage function is triggered successfully. Although the provided data field of MessageEvent is empty.
My Implementation
Main.java
private SSEHandler sseHandler = new SSEHandler();
private EventSource eventSource;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startEventSource();
}
private void startEventSource() {
eventSource = new EventSource.Builder(".../ambulance/assign/receive")
.eventHandler(sseHandler)
// .headers()
.build();
eventSource.connect();
}
private void stopEventSource() {
if (eventSource != null)
eventSource.close();
sseHandler = null;
}
SSEHandler.java
public class SSEHandler implements EventSourceHandler {
public SSEHandler() {}
#Override
public void onConnect() {
Log.e("SSE Connected", "True");
}
#Override
public void onMessage(String event, MessageEvent message) {
Log.e("SSE Message", event);
Log.e("SSE Message: ", String.valueOf(message));
}
#Override
public void onComment(String comment) {
//comments only received if exposeComments turned on
Log.e("SSE Comment", comment);
}
#Override
public void onError(Throwable t) {
//ignore ssl NPE on eventSource.close()
Log.e("SSE Error", "Error");
}
#Override
public void onClosed(boolean willReconnect) {
Log.e("SSE Closed", "reconnect? " + willReconnect);
}
}
Server Side Endpoint
#RequestMapping(method = RequestMethod.GET, value = "/ambulance/assign/receive")
public Flux < MessageEvent > addReport() {
return Flux.create(sink -> {
assignProcessor.register(sink::next);
});
}
No matter what is the return type of Flux <Object> the data field
is always empty on android
POST payload & MessageEvent Object
Payload
{
"data": "test",
"lastEventId": "tester",
"origin": "my origin"
}
MessageEvent.java
public class MessageEvent {
public String data;
public String lastEventId;
public String origin;
public MessageEvent(String data, String lastEventId, String origin) {
this.data = data;
this.lastEventId = lastEventId;
this.origin = origin;
}
public MessageEvent(String data) {
this(data, null, null);
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
MessageEvent that = (MessageEvent) o;
if (data != null ? !data.equals(that.data) : that.data != null) return false;
if (lastEventId != null ? !lastEventId.equals(that.lastEventId) : that.lastEventId != null) return false;
if (origin != null ? !origin.equals(that.origin) : that.origin != null) return false;
return true;
}
#Override
public int hashCode() {
int result = data != null ? data.hashCode() : 0;
result = 31 * result + (lastEventId != null ? lastEventId.hashCode() : 0);
result = 31 * result + (origin != null ? origin.hashCode() : 0);
return result;
}
#Override
public String toString() {
return "MessageEvent{" +
"data='" + data + '\'' +
", lastEventId='" + lastEventId + '\'' +
", origin='" + origin + '\'' +
'}';
}
}
Already tried with : Flux <String> data is still empty.
Based on this EventStreamParser I assume that it should parse as data every Object in JSON format because of this function.
private void processField(String field, String value)
I even tried plain text, but didn't seem to work either...
I managed to read the Object using another java library
This one:
Maven
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.7.2</version>
</dependency>
Gradle
// https://mvnrepository.com/artifact/com.squareup.okhttp3/okhttp
compile group: 'com.squareup.okhttp3', name: 'okhttp', version: '4.7.2'
Buildr
# https://mvnrepository.com/artifact/com.squareup.okhttp3/okhttp
'com.squareup.okhttp3:okhttp:jar:4.7.2'
Implemented EventSource as before
public class SimpleEventHandler implements EventHandler {
#Override
public void onOpen() throws Exception {
System.out.println("onOpen");
}
#Override
public void onClosed() throws Exception {
System.out.println("onClosed");
}
#Override
public void onMessage(String event, MessageEvent messageEvent) throws Exception {
System.out.println(messageEvent.getData());
}
#Override
public void onComment(String comment) throws Exception {
System.out.println("onComment");
}
#Override
public void onError(Throwable t) {
System.out.println("onError: " + t);
}
}
Main method
public static void main(String[] args) throws InterruptedException, ExecutionException, UnknownHostException, IOException {
EventHandler eventHandler = new SimpleEventHandler();
String url = String.format("https://aedproject.herokuapp.com/api/ambulance/assign/receive");
EventSource.Builder builder = new EventSource.Builder(eventHandler, URI.create(url))
.reconnectTime(Duration.ofMillis(3000));
try (EventSource eventSource = builder.build()) {
eventSource.start();
TimeUnit.MINUTES.sleep(10);
} catch (Exception e) {
}
This time, the data filed of MessageEvent contains my whole Object!

An authentication problem occurs in the Android web socket

I try to connect to the server using a web socket, but this error occurs.
java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.
Here's my code for the connection.
private final class EchoWebSocketListener extends WebSocketListener {
#Override
public void onOpen(WebSocket webSocket, Response response) {
webSocket.send("text");
}
#Override
public void onMessage(WebSocket webSocket, String text) {
output("Receiving : " + text);
}
#Override
public void onMessage(WebSocket webSocket, ByteString bytes) {
output("Receiving bytes : " + bytes.hex());
}
#Override
public void onClosing(WebSocket webSocket, int code, String reason) {
webSocket.close(NORMAL_CLOSURE_STATUS, null);
output("Closing : " + code + " / " + reason);
}
#Override
public void onFailure(WebSocket webSocket, Throwable t, Response response) {
output("Error : " + t.getMessage());
}
}
private void start() {
Request request = new Request.Builder().url("wss://xxx.xxx.xxx.xxx:8443/one2many").build();
EchoWebSocketListener listener = new EchoWebSocketListener();
WebSocket ws = client.newWebSocket(request, listener);
client.dispatcher().executorService().shutdown();
}
}
I am staying in this problem and I want you to help me!

How to show response errorBody in Retrofit on Android

In my app, I want to use Retrofit2 to connect to the server and get some data.
For this, I've written the code as shown below but it doesn't show the data. And for some reason, no (detailed) error is outputted.
private void getDetailData(String auctionID, final String jwtToken) {
showLoading(true);
Call<DetailResponse> call = apis.getDetainAuctions(auctionID, jwtToken, agent);
call.enqueue(new Callback<DetailResponse>() {
#Override
public void onResponse(Call<DetailResponse> call, final Response<DetailResponse> response) {
Log.e("detailLog", "OK");
Log.e("detailLog", response.message() + " --- " + response.errorBody());
if (response.isSuccessful()) {
}
}
#Override
public void onFailure(Call<DetailResponse> call, Throwable t) {
Log.e("detailLog", "Err : " + t.getMessage());
}
});
}
Logcat error:
E/detailLog: --- okhttp3.ResponseBody$1#cbf85bc
What does the error mean?

Omegle Java API Doesn't Work

I am attempting to use the Omegle Java API found here: https://github.com/nikkiii/omegle-api-java. However, the following code:
package me.nrubin29.pollmegle;
import org.nikki.omegle.Omegle;
import org.nikki.omegle.core.OmegleMode;
import org.nikki.omegle.core.OmegleSession;
import org.nikki.omegle.core.OmegleSpyStranger;
import org.nikki.omegle.event.OmegleEventAdaptor;
import java.util.Map;
public class Pollmegle {
public static void main(String[] args) {
Omegle omegle = new Omegle();
final String question = "Yes or no?";
System.out.println(question);
try {
OmegleSession session = omegle.openSession(OmegleMode.SPY_QUESTION, question, new OmegleEventAdaptor() {
#Override
public void chatWaiting(OmegleSession session) {
System.out.println("Waiting for chat...");
}
#Override
public void chatConnected(OmegleSession session) {
System.out.println("You are now watching two strangers talk about \"" + question + "\"!");
}
#Override
public void spyMessage(OmegleSession session, OmegleSpyStranger stranger, String message) {
System.out.println(stranger + ": " + message);
}
#Override
public void spyDisconnected(OmegleSession session, OmegleSpyStranger stranger) {
System.out.println("Stranger "+stranger+" disconnected, goodbye!");
System.exit(0);
}
#Override
public void question(OmegleSession session, String question) {
System.out.println("Question: "+question);
}
#Override
public void omegleError(OmegleSession session, String string) {
System.out.println("ERROR! " + string);
System.exit(1);
}
#Override
public void recaptchaRequired(OmegleSession session, Map<String, Object> variables) {
System.out.print("Required // ");
for (String var : variables.keySet()) {
System.out.println(var + " // " + variables.get(var));
}
}
#Override
public void recaptchaRejected(OmegleSession session, Map<String, Object> variables) {
System.out.println("Rejected // ");
for (String var : variables.keySet()) {
System.out.println(var + " // " + variables.get(var));
}
}
});
System.out.println("Session " + session.getId() + " created.");
omegle.setEventParseDelay(1000);
omegle.run();
}
catch (Exception e) { e.printStackTrace(); }
}
}
Yields this result:
Yes or no?
Required // 6Led7gkAAAAAAEAyh-Kt7HTb_oC0chDvQIZ8VtQb // null
Session central1:znv479i7a5sh2u60z5sg6s2nzm6jpb created.
What am I doing wrong? Do I need to pass a captcha?
no, its supposed to output this. but when i ran the code i kept getting "enum not found errors" so i went into org.nikki.omegle.core.OmegleEvent and added the lines
,statusInfo,identDigests
to the bottom and it worked like a charm. Are you getting the same enum not found errors?
Turns out the problem isn't the API, it's that my IP address was flagged and I needed to enter a reCAPTCHA every time I started a chat. It works.

Categories

Resources