I'm learning to use the Telegram client api (not the bot api). I'm currently trying out simple things to try to understand how things work. I'm currently trying to retrieve information about a channel but not managing to.
From what I searched, there's very little documentation, examples and no tutorials. If you possibly know of tutorials, I would be very thankful if you shared them with me.
Method I'm using to retrieve info:
public static void printChatInfo(int chatId) {
try {
TLRequestChannelsGetChannels request = new TLRequestChannelsGetChannels();
TLIntVector ints = new TLIntVector();
ints.add(chatId);
request.setId(ints);
TLVector<TLAbsChat> chats = bot.getKernelComm().doRpcCallSync(request).getChats();
for (TLAbsChat chat : chats) {
System.out.println("*****************************" +
"\n*****************************" +
"\n*****************************" +
"\n*****************************" +
"\n*****************************");
System.out.println(chat.getId());
if (chat instanceof TLChat) {
TLChat chatCast = (TLChat) chat;
System.out.println(chatCast.getTitle());
} else {
System.out.println("NOT INSTANCE");
}
System.out.println("*****************************" +
"\n*****************************" +
"\n*****************************" +
"\n*****************************" +
"\n*****************************");
}
} catch (Exception e) {
e.printStackTrace();
}
}
Where it's being called:
public void onTLMessage(TLMessage message) {
final TLAbsPeer absPeer = message.getToId();
System.out.println(message.getMessage());
Deepthought.printChatInfo(message.getChatId());
if (absPeer instanceof TLPeerUser) {
onTLMessageForUser(message);
} else {
BotLogger.severe(LOGTAG, "Unsupported Peer: " + absPeer.toString());
}
}
System.out.println(message.getMessage()); is working correctly.
The exceptions at TLVector<TLAbsChat> chats = bot.getKernelComm().doRpcCallSync(request).getChats();:
java.util.concurrent.ExecutionException: org.telegram.api.engine.RpcException: INPUT_CONSTRUCTOR_INVALID_04A42D7B
at java.base/java.util.concurrent.FutureTask.report(FutureTask.java:122)
at java.base/java.util.concurrent.FutureTask.get(FutureTask.java:191)
at org.telegram.bot.kernel.KernelComm.doRpcCallSync(KernelComm.java:185)
at org.telegram.Deepthought.printChatInfo(Deepthought.java:97)
at org.telegram.plugins.echo.handlers.TLMessageHandler.onTLMessage(TLMessageHandler.java:30)
at org.telegram.plugins.echo.CustomUpdatesHandler.onTLMessage(CustomUpdatesHandler.java:98)
at org.telegram.plugins.echo.CustomUpdatesHandler.onTLAbsMessageCustom(CustomUpdatesHandler.java:74)
at org.telegram.plugins.echo.CustomUpdatesHandler.onTLUpdateNewMessageCustom(CustomUpdatesHandler.java:67)
at org.telegram.bot.handlers.UpdatesHandlerBase.onTLUpdateNewMessage(UpdatesHandlerBase.java:327)
at org.telegram.bot.handlers.UpdatesHandlerBase.processUpdate(UpdatesHandlerBase.java:122)
at org.telegram.bot.kernel.MainHandler$UpdateHandlerThread.run(MainHandler.java:305)
Caused by: org.telegram.api.engine.RpcException: INPUT_CONSTRUCTOR_INVALID_04A42D7B
at org.telegram.api.engine.TelegramApi$2.onError(TelegramApi.java:345)
at org.telegram.api.engine.TelegramApi$ProtoCallback.onRpcError(TelegramApi.java:851)
at org.telegram.mtproto.MTProto.onMTProtoMessage(MTProto.java:375)
at org.telegram.mtproto.MTProto.onMTMessage(MTProto.java:255)
at org.telegram.mtproto.MTProto.access$1300(MTProto.java:44)
at org.telegram.mtproto.MTProto$ResponseProcessor.run(MTProto.java:754)
java.lang.NullPointerException
at org.telegram.Deepthought.printChatInfo(Deepthought.java:97)
at org.telegram.plugins.echo.handlers.TLMessageHandler.onTLMessage(TLMessageHandler.java:30)
at org.telegram.plugins.echo.CustomUpdatesHandler.onTLMessage(CustomUpdatesHandler.java:98)
at org.telegram.plugins.echo.CustomUpdatesHandler.onTLAbsMessageCustom(CustomUpdatesHandler.java:74)
at org.telegram.plugins.echo.CustomUpdatesHandler.onTLUpdateNewMessageCustom(CustomUpdatesHandler.java:67)
at org.telegram.bot.handlers.UpdatesHandlerBase.onTLUpdateNewMessage(UpdatesHandlerBase.java:327)
at org.telegram.bot.handlers.UpdatesHandlerBase.processUpdate(UpdatesHandlerBase.java:122)
at org.telegram.bot.kernel.MainHandler$UpdateHandlerThread.run(MainHandler.java:305)
I appreciate any ideas that might solve or help solve this problem.
Thanks.
Related
I am trying to implement GRPC and when i do so I get the correct response from the server and if I stop the server and run it again and use the other request that I implemented it works however if I try and make a second request straight after making one in from the first request I get the same response. It's like it is looping.
These are the two methods I am using from the client:
public void setSpaces(int id) {
channel =ManagedChannelBuilder.forAddress("localhost", 3000)
// Channels are secure by default (via SSL/TLS). For the example we disable TLS to avoid
// needing certificates.
.usePlaintext()
.build();
blockingStub = carParkServiceGrpc.newBlockingStub(channel);
asyncStub = carParkServiceGrpc.newStub(channel);
logger.info("Will try to get CarPark " + id + " ...");
CarParkToUpdateRequest request = CarParkToUpdateRequest.newBuilder().setDeviceId(id).build();
carParkResponse response;
try {
response = blockingStub.setSpaces(request);
}catch(StatusRuntimeException e) {
logger.log(Level.WARNING, "RPC failed: {0}", e.getStatus());
return;
}finally {
channel.shutdown();
}
logger.info("Carpark: " + response.getCarPark());
spacesArea.append(response.getCarPark().toString());
}
public void setFull(int id) {
channel =ManagedChannelBuilder.forAddress("localhost", 3000)
// Channels are secure by default (via SSL/TLS). For the example we disable TLS to avoid
// needing certificates.
.usePlaintext()
.build();
blockingStub = carParkServiceGrpc.newBlockingStub(channel);
asyncStub = carParkServiceGrpc.newStub(channel);
logger.info("Will try to get CarPark " + id + " ...");
CarParkToUpdateRequest request = CarParkToUpdateRequest.newBuilder().setDeviceId(id).build();
carParkResponse response;
try {
response = blockingStub.setFull(request);
}catch(StatusRuntimeException e) {
logger.log(Level.WARNING, "RPC failed: {0}", e.getStatus());
return;
}finally {
channel.shutdown();
}
logger.info("Carpark: " + response.getCarPark());
fullArea.append(response.getCarPark().toString());
}
These two methods are supposed to send a request to the server to change the status of the 'car park' so if I send a request with setFull I get a response saying the carpark is full etc.
These are the methods from the server:
public void setSpaces(CarParkToUpdateRequest request, StreamObserver<carParkResponse> rStreamObserver) {
ArrayList<CarParkOperations.proto.cp.CarPark> carList = Car.getInstance();
for(int i=0; i<carList.size(); i++) {
if(carList.get(i).getCarParkId() == request.getDeviceId()) {
CarParkOperations.proto.cp.CarPark heater_rec = (CarParkOperations.proto.cp.CarPark) carList.get(i);
Car.carparkCar.clear();
Car.carparkCar.add(CarParkOperations.proto.cp.CarPark.newBuilder().setCarParkId(heater_rec.getCarParkId()).setLocation(heater_rec.getLocation()).setStatus("Spaces").build());
}
}
for(CarParkOperations.proto.cp.CarPark heater : Car.carparkCar) {
carParkResponse response = carParkResponse.newBuilder().setCarPark(heater).build();
rStreamObserver.onNext(response);
rStreamObserver.onCompleted();
return;
}
}
public void setFull(CarParkToUpdateRequest request, StreamObserver<carParkResponse> rStreamObserver) {
ArrayList<CarParkOperations.proto.cp.CarPark> carList = Car.getInstance();
for(int i=0; i<carList.size(); i++) {
if(carList.get(i).getCarParkId() == request.getDeviceId()) {
CarParkOperations.proto.cp.CarPark heater_rec = (CarParkOperations.proto.cp.CarPark) carList.get(i);
Car.carparkCar.clear();
Car.carparkCar.add(CarParkOperations.proto.cp.CarPark.newBuilder().setCarParkId(heater_rec.getCarParkId()).setLocation(heater_rec.getLocation()).setStatus("Full").build());
}
}
for(CarParkOperations.proto.cp.CarPark heater : Car.carparkCar) {
carParkResponse response = carParkResponse.newBuilder().setCarPark(heater).build();
rStreamObserver.onNext(response);
rStreamObserver.onCompleted();
return;
}
}
I think it's most likely something to do with the server methods but cant seem to figure it out.
This is where I am storing the data:
package CarParkOperations.proto.cp;
import java.util.ArrayList;
import com.google.rpc.Status;
public class Car extends ArrayList<CarPark>{
public static Car carparkCar;
public static Car getInstance() {
if(carparkCar == null) {
carparkCar = new Car();
}
return carparkCar;
}
public Car() {
this.add(CarParkOperations.proto.cp.CarPark.newBuilder().setCarParkId(1).setStatus("Full").setLocation("Behind Building 1").build());
this.add(CarParkOperations.proto.cp.CarPark.newBuilder().setCarParkId(2).setStatus("Full").setLocation("Behind Building 1").build());
this.add(CarParkOperations.proto.cp.CarPark.newBuilder().setCarParkId(3).setStatus("Full").setLocation("Behind Building 4").build());
this.add(CarParkOperations.proto.cp.CarPark.newBuilder().setCarParkId(4).setStatus("Full").setLocation("Behind Building 3").build());
this.add(CarParkOperations.proto.cp.CarPark.newBuilder().setCarParkId(5).setStatus("Full").setLocation("Behind Building 2").build());
this.add(CarParkOperations.proto.cp.CarPark.newBuilder().setCarParkId(6).setStatus("Full").setLocation("Behind Building 1").build());
this.add(CarParkOperations.proto.cp.CarPark.newBuilder().setCarParkId(7).setStatus("Full").setLocation("Behind Building 1").build());
this.add(CarParkOperations.proto.cp.CarPark.newBuilder().setCarParkId(10).setStatus("Full").setLocation("Behind Building 6").build());
this.add(CarParkOperations.proto.cp.CarPark.newBuilder().setCarParkId(11).setStatus("Full").setLocation("Behind Building 1").build());
this.add(CarParkOperations.proto.cp.CarPark.newBuilder().setCarParkId(12).setStatus("Spaces").setLocation("Behind Building 1").build());
this.add(CarParkOperations.proto.cp.CarPark.newBuilder().setCarParkId(13).setStatus("Spaces").setLocation("Behind Building 1").build());
this.add(CarParkOperations.proto.cp.CarPark.newBuilder().setCarParkId(14).setStatus("Spaces").setLocation("Behind Building 1").build());
}
}
Any suggestions would be much appreciated.
You might need synchronize Car.getInstance() method, because without proper synchronization, if it is called by different threads it may surprisingly return different instances!
public static synchronized Car getInstance() {
if(carparkCar == null) {
carparkCar = new Car();
}
return carparkCar;
}
Also your Car class is not thread-safe because it extends ArrayList which is not thread-safe. You should let your Car class extend something like ConcurrentLinkedQueue instead, or let your Car class compose a field of list = Collections.synchronizedList(new ArrayList()) instead of extending ArrayList.
I want to change Web Application's class loader order to PARENT_LAST using WebSphere Java Administration API.
Enterprise Applications > MyAppEAR > Manage Modules > MyApp.war
How to get the attribute to set using ConfigService.
Tried the below code which threw
java.lang.ClassCastException: java.util.ArrayList cannot be cast to javax.management.AttributeList
at com.kony.admin.deployment.websphere.KonyWebsphereDeployer.updateArtifact(KonyWebsphereDeployer.java:1854)
AttributeList clList = (AttributeList) configService.getAttribute (session, appDeplID, "modules");
ConfigServiceHelper.setAttributeValue (clList, "classloaderMode", "PARENT_LAST");
attrList.add (new Attribute ("modules", clList));
Thanks,
Kusuma
Below is the solution
private void updateArtifactConfig(String appName, DeploymentConfig dc)
throws DeploymentException {
Session session = new Session();
try {
ObjectName[] classLoadersId = configService.resolve(session,
"Deployment=" + appName + "\":ApplicationDeployment:WebModuleDeployment:");
AttributeList attrList = new AttributeList();
AttributeList clList = (AttributeList)configService.getAttribute(session, classLoadersId[0],
"classloader");
ConfigServiceHelper.setAttributeValue(clList, "mode",
"PARENT_LAST");
attrList.add(new Attribute("classloader", clList));
configService.setAttributes(session, classLoadersId[0], attrList);
configService.save(session, true);
} catch (Exception ex) {
LOGGER.error("Not able to update " + appName, ex);
} finally {
try {
configService.discard(session);
} catch (ConfigServiceException csEx) {
LOGGER.error("Not able to discard updateArtifact " + appName + " session", csEx);
} catch (ConnectorException cnEx) {
throw new DeploymentException("Unable to connect to IBM WebSphere Application Server # "
+ dc.getHostname() + ":" + dc.getPort());
}
}
}
i am using grails 3.1.1
i already try to find some documentation and question like this.
this is my code in ChatController
class ChatController {
SimpMessagingTemplate brokerMessagingTemplate
def corporateUserService
def index={
}
#MessageMapping("/chat")
#SendTo("/queue/chat")
protected String hello(DestinationUser map) {
brokerMessagingTemplate.convertAndSend "/queue/chat", map
}
}
and i already deploy this application, for example :
https://somedomain.com
how can i connect from android to my webapplication's websocket?
i tried
wss://somedomain.com/chat
wss://somedomain.com/queue/chat
but it still cannot connect.
i am trying follow this tutorial github
like this..
AsyncHttpClient.getDefaultInstance().websocket("ws://satubangau.com/app/hello", null, new AsyncHttpClient.WebSocketConnectCallback() {
#Override
public void onCompleted(Exception ex, WebSocket webSocket) {
Log.d(TAG, "onCompleted: ");
if (ex != null) {
ex.printStackTrace();
return;
}
webSocket.send("a string");
webSocket.send(new byte[10]);
webSocket.setStringCallback(new WebSocket.StringCallback() {
public void onStringAvailable(String s) {
Log.d(TAG, "onStringAvailable: I got a string: " + s);
}
});
webSocket.setDataCallback(new DataCallback() {
public void onDataAvailable(DataEmitter emitter, ByteBufferList byteBufferList) {
Log.d(TAG, "onDataAvailable: I got some bytes!");
// note that this data has been read
byteBufferList.recycle();
}
});
}
});
but i get the log like this..
Have you tried using a WebSocket client library on Android, e.g. https://github.com/koush/AndroidAsync ?
I'm looking for one way to share a non-parcelable item from my application and my current Service. This is the situation:
I have a Service to store all the media data from a camera application, photos, videos etc. The mission of this service is continue saving the media when the user go to background. When I did this in a first instance, I had a lot of SIGSEGV errors:
08-22 10:15:49.377 15784-15818/com.bq.camerabq A/libc: Fatal signal 11 (SIGSEGV), code 1, fault addr 0x8c3f4000 in tid 15818 (CameraModuleBac)
This was because the Image item that I recover from my imageReaders are not parceable, I fix this saving the Bytebuffers from the image instead of the whole image item.
But, now I'm getting the same problem with DNG captures, because from my imageReader I got a CaptureResult item that I need to use to create a DngCreator item to write the dng image.
CaptureResults and DngCreators are not parcelables or Serializables, so I don't find a way to save my data from the application to recover it in the service if I'm in background.
I have tried to copy the reference when calling the Service and it didn't worked. Also I saw in other posts as Object Sharing Between Activities in Android and Object Sharing Between Activities in Android that I can save the item in a static reference in my application context to be able to recover it in different activities. So finally I tried this:
public class DngManager extends Application {
public static DngManager sDngManagerInstance;
protected Hashtable<String, CaptureResult> dngCaptureResults;
private static String DNG_KEY_PREFIX = "dngResult_";
public DngManager(){
super();
createDNGCaptureResults();
}
public void createDNGCaptureResults() {
dngCaptureResults = new Hashtable<String, CaptureResult>();
}
public boolean addDNGCaptureResultToSharedMem(long dateKey, CaptureResult value) {
dngCaptureResults.put(DNG_KEY_PREFIX + dateKey, value);
return true;
}
public CaptureResult getFromDNGCaptureResults(long dateKey) {
return dngCaptureResults.get(DNG_KEY_PREFIX + dateKey);
}
private boolean containsDNGCaptureResults(long dateKey) {
return dngCaptureResults.containsKey(DNG_KEY_PREFIX + dateKey);
}
public void clearDNGCaptureResults(long dateKey) {
String partKey = String.valueOf(dateKey);
Enumeration<String> e2 = dngCaptureResults.keys();
while (e2.hasMoreElements()) {
String i = (String) e2.nextElement();
if (i.contains(partKey))
dngCaptureResults.remove(i);
}
}
public static DngManager getInstance(){
if (sDngManagerInstance == null){
sDngManagerInstance = new DngManager();
}
return sDngManagerInstance;
}
}
And later I recover it in my service:
CaptureResult dngResult = ((DngManager)getApplication()).getFromDNGCaptureResults(mDngPicture.getDateTaken());
if (dngResult == null) {
return;
}
DngCreator dngCreator = new DngCreator(mCameraCharacteristics, dngResult);
path = Storage.generateFilepath(title, "dng");
file = new File(Uri.decode(path));
try {
Log.e(TAG, "[DngSaveTask|run] WriteByteBuffer: Height " + mDngPicture.getSize().getHeight() + " Width " + mDngPicture.getSize().getWidth());
OutputStream os = new FileOutputStream(file);
dngCreator.writeByteBuffer(os, mDngPicture.getSize(), mDngPicture.getDngByteBuffer(), 0);
} catch (IOException e) {
Log.d(TAG, "[DngSaveTask|run] " + e);
e.printStackTrace();
}
dngCreator.close();
Log.e(TAG, "[DngSaveTask|run] Cleaning Result from shared memory");
DngManager.getInstance().clearDNGCaptureResults(mDngPicture.getDateTaken());
MediaScannerConnection.scanFile(getApplicationContext(), new String[]{file.getAbsolutePath()}, null, null);
Anyway, it still giving me back a SIGSEGV error. What else can I try?
can anyone please tell me how to use google places api in android. I am developing this application in eclipse where i need to find the nearest petrol stations and garages near my area. I went through numerous websites. i didnt find a proper answer. I need a sample code since i am new to json concepts.
public class place {
private static final String PLACES_SEARCH_URL = "https://maps.googleapis.com/maps/api/place/search/json?";
private static final boolean PRINT_AS_STRING = false;
public void performSearch() throws Exception {
try {
System.out.println("Perform Search ....");
System.out.println("-------------------");
HttpRequestFactory httpRequestFactory = createRequestFactory(transport);
HttpRequest request = httpRequestFactory.buildGetRequest(new GenericUrl(PLACES_SEARCH_URL));
request.url.put("key", "api key");
request.url.put("location", lat + "," + lng);
request.url.put("radius", 500);
request.url.put("sensor", "false");
if (PRINT_AS_STRING) {
System.out.println(request.execute().parseAsString());
} else {
PlacesList places = request.execute().parseAs(PlacesList.class);
System.out.println("STATUS = " + places.status);
for (Place place : places.results) {
System.out.println(place);
}
}
} catch (HttpResponseException e) {
System.err.println(e.response.parseAsString());
throw e;
}
}//StoresNearMe
You can use Google API Java Client for Google Places API in Android . See my answer for a short snippet https://stackoverflow.com/a/12824796/1147466