When i am using this code it gives error:
2011-08-10 13:18:13.368::WARN: EXCEPTION
java.lang.IllegalAccessError: tried to access method org.mortbay.util.Utf8StringBuffer.(I)V from class org.mortbay.jetty.HttpURI
Code:
package com.google.api.client.sample.docs.v3;
import com.google.api.client.auth.oauth.OAuthCredentialsResponse;
import com.google.api.client.auth.oauth.OAuthHmacSigner;
import com.google.api.client.auth.oauth.OAuthParameters;
import com.google.api.client.googleapis.auth.oauth.GoogleOAuthAuthorizeTemporaryTokenUrl;
import com.google.api.client.googleapis.auth.oauth.GoogleOAuthGetAccessToken;
import com.google.api.client.googleapis.auth.oauth.GoogleOAuthGetTemporaryToken;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.sample.docs.v3.model.DocsUrl;
import java.awt.Desktop;
import java.awt.Desktop.Action;
import java.net.URI;
public class Auth {
private static final String APP_NAME ="Google Documents List Data API Java Client Sample";
private static OAuthHmacSigner signer;
private static OAuthCredentialsResponse credentials;
static void authorize(HttpTransport transport) throws Exception {
// callback server
LoginCallbackServer callbackServer = null;
String verifier = null;
String tempToken = null;
try {
callbackServer = new LoginCallbackServer();
callbackServer.start();
// temporary token
GoogleOAuthGetTemporaryToken temporaryToken =new GoogleOAuthGetTemporaryToken();
signer = new OAuthHmacSigner();
signer.clientSharedSecret = "anonymous";
temporaryToken.signer = signer;
temporaryToken.consumerKey = "in.gappsdemo.in";
//temporaryToken.scope ="https://apps-apis.google.com/a/feeds/user/";
temporaryToken.scope = DocsUrl.ROOT_URL;
temporaryToken.displayName = APP_NAME;
temporaryToken.callback = callbackServer.getCallbackUrl();
System.out.println("temporaryToken.callback: "+temporaryToken.callback);
OAuthCredentialsResponse tempCredentials = temporaryToken.execute();
signer.tokenSharedSecret = tempCredentials.tokenSecret;
System.out.println("signer.tokenSharedSecret: " + signer.tokenSharedSecret);
// authorization URL
GoogleOAuthAuthorizeTemporaryTokenUrl authorizeUrl =new GoogleOAuthAuthorizeTemporaryTokenUrl();
authorizeUrl.temporaryToken = tempToken = tempCredentials.token;
String authorizationUrl = authorizeUrl.build();
System.out.println("Go to this authorizationUrl: " + authorizationUrl);
// launch in browser
boolean browsed = false;
if (Desktop.isDesktopSupported()) {
Desktop desktop = Desktop.getDesktop();
if (desktop.isSupported(Action.BROWSE)) {
System.out.println("In if browsed condition:");
desktop.browse(URI.create(authorizationUrl));
browsed = true;
}
}
if (!browsed) {
String browser = "google-chrome";
Runtime.getRuntime().exec(new String[] {browser, authorizationUrl});
System.out.println("In if !browsed condition1:");
}
System.out.println("tempToken: "+tempToken);
verifier = callbackServer.waitForVerifier(tempToken);
System.out.println("GoogleOAuthGetAccessToken: ");
} finally {
System.out.println("server Stop:");
if (callbackServer != null) {
System.out.println("server Stop:");
callbackServer.stop();
}
}
System.out.println("GoogleOAuthGetAccessToken: ");
GoogleOAuthGetAccessToken accessToken = new GoogleOAuthGetAccessToken();
accessToken.temporaryToken = tempToken;
accessToken.signer = signer;
accessToken.consumerKey = "in.gappsdemo.in";
accessToken.verifier = verifier;
credentials = accessToken.execute();
signer.tokenSharedSecret = credentials.tokenSecret;
System.out.println("signer.tokenSharedSecret: ");
createOAuthParameters().signRequestsUsingAuthorizationHeader(transport);
}
static void revoke() {
if (credentials != null) {
try {
GoogleOAuthGetAccessToken.revokeAccessToken(createOAuthParameters());
} catch (Exception e) {
e.printStackTrace(System.err);
}
}
}
private static OAuthParameters createOAuthParameters() {
OAuthParameters authorizer = new OAuthParameters();
authorizer.consumerKey = "in.gappsdemo.in";
authorizer.signer = signer;
authorizer.token = credentials.token;
return authorizer;
}
}
Here are two potentially related, posts. Notice you're getting an Error, not an Exception, so that is interesting. You might try running your JVM with -verbose to see where each class is getting loaded from, to see if maybe you're compiling with one class/jar, but accidentally running with another.
Also notice from the error that the packages are slightly different "org.mortbay.util" vs. "org.mortbay.jetty", so the UTF8StringBuffer constructor would need to be more visible. But again, normally a compiler would catch that.
I realize this isn't a full answer, to be sure, but at least a couple places to start looking.
Related
I'm using snmp4j 3.4.2 inside my java application (full code below)
I'm trying to execute a snmpget with snmpv3, security DES and auth MD5 and custom OID (python script, which is executed by snmp's extend funtionality). To create better understanding I used SnmpConstants.sysUpTime in the example below.
The SNMP resource has this user configured:
defSecurityName demo
defSecurityLevel authPriv
defAuthType MD5
defPrivType DES
defAuthPassphrase pass
defPrivPassphrase pass
I'm already using this user and resource to successfully perform the snmpget with python (pysnmp) and bash (snmpget), so I can definitely tell that my setup works and the java code is the problem.
I have two java classes (Listener.java and ServerStatusHelper.java)
Listener.java contains main and calls the snmpGet inside ServerStatusHelper.java, other code of Listener is excluded as its not neccessary.
import org.snmp4j.PDU;
import org.snmp4j.ScopedPDU;
import org.snmp4j.Snmp;
import org.snmp4j.Target;
import org.snmp4j.event.ResponseEvent;
import org.snmp4j.mp.SnmpConstants;
import org.snmp4j.security.AuthMD5;
import org.snmp4j.security.AuthSHA;
import org.snmp4j.security.PrivAES128;
import org.snmp4j.security.PrivDES;
import org.snmp4j.smi.OID;
import org.snmp4j.smi.VariableBinding;
public class Listener {
public static void main(String[] args) {
ServerStatusHelper agent = new ServerStatusHelper("host.tld", "udp", 161, "demo", "demo",
"pass", "pass", new AuthMD5(), new PrivDES(), true);
try {
agent.startAgent();
ResponseEvent response = agent.snmpGetOperation(SnmpConstants.sysUpTime);
if (response != null) {
System.out.println(
"response null - error: "+ response.getError() +
"peerAddress: " + response.getPeerAddress() +
"source: " + response.getSource().toString() +
"request: " + response.getRequest());
}
} catch (
IOException e) {
e.printStackTrace();
}
}
}
ServerStatusHelper.java
import java.io.IOException;
import org.snmp4j.CommunityTarget;
import org.snmp4j.PDU;
import org.snmp4j.ScopedPDU;
import org.snmp4j.Snmp;
import org.snmp4j.TransportMapping;
import org.snmp4j.UserTarget;
import org.snmp4j.event.ResponseEvent;
import org.snmp4j.mp.MPv3;
import org.snmp4j.mp.SnmpConstants;
import org.snmp4j.security.AuthGeneric;
import org.snmp4j.security.AuthMD5;
import org.snmp4j.security.PrivDES;
import org.snmp4j.security.PrivacyGeneric;
import org.snmp4j.security.SecurityLevel;
import org.snmp4j.security.SecurityModels;
import org.snmp4j.security.SecurityProtocols;
import org.snmp4j.security.USM;
import org.snmp4j.security.UsmUser;
import org.snmp4j.smi.Address;
import org.snmp4j.smi.GenericAddress;
import org.snmp4j.smi.OID;
import org.snmp4j.smi.OctetString;
import org.snmp4j.smi.TransportIpAddress;
import org.snmp4j.smi.VariableBinding;
import org.snmp4j.transport.DefaultTcpTransportMapping;
import org.snmp4j.transport.DefaultUdpTransportMapping;
public class ServerStatusHelper {
private Address nmsIP;
private String user;
private String securityName;
private String privacyPassword;
private String authorizationPassword;
private AuthGeneric authProtocol;
private PrivacyGeneric privacyProtocol;
private String protocol;
private boolean encryption;
private long timeOut = 1000;
private int noOfRetries = 10;
private Snmp snmp;
private UserTarget target;
private CommunityTarget v1target;
ServerStatusHelper(String ip, String protocol, int snmpPort, String username, String securityName,
String privacyPassword, String authPassowrd, AuthGeneric authProtocol, PrivacyGeneric privacyProtocol,
boolean encryption) {
nmsIP = GenericAddress.parse(protocol + ":" + ip + "/" + snmpPort);
System.out.println("NMS IP set : " + nmsIP.toString());
this.protocol = protocol;
this.user = username;
this.securityName = securityName;
this.privacyPassword = privacyPassword;
this.authorizationPassword = authPassowrd;
this.authProtocol = authProtocol;
this.privacyProtocol = privacyProtocol;
this.encryption = encryption;
SecurityProtocols.getInstance().addAuthenticationProtocol(new AuthMD5());
SecurityProtocols.getInstance().addPrivacyProtocol(new PrivDES());
}
public void startAgent() throws IOException {
if (snmp == null) {
TransportMapping<? extends TransportIpAddress> transport = null;
if (protocol.equalsIgnoreCase("udp")) {
System.out.println("UDP Protocol selected.");
transport = new DefaultUdpTransportMapping();
} else {
System.out.println("TCP Protocol selected.");
transport = new DefaultTcpTransportMapping();
}
snmp = new Snmp(transport);
USM usm = new USM(SecurityProtocols.getInstance(), new OctetString(MPv3.createLocalEngineID()), 0);
SecurityModels.getInstance().addSecurityModel(usm);
transport.listen();
snmp.getUSM().addUser(new OctetString(user),
new UsmUser(new OctetString(securityName), authProtocol.getID(),
new OctetString(authorizationPassword), privacyProtocol.getID(),
new OctetString(privacyPassword)));
if (encryption)
target = createUserTarget();
else
v1target = createUserTargetWithoutEncryption();
}
}
public ResponseEvent snmpSetOperation(VariableBinding[] vars) throws IOException {
PDU setPdu = new ScopedPDU();
for (VariableBinding variableBinding : vars) {
setPdu.add(variableBinding);
}
return snmp.send(setPdu, target);
}
public ResponseEvent snmpGetOperation(OID oid) throws IOException {
if (encryption) {
PDU getPdu = new ScopedPDU();
getPdu.add(new VariableBinding(oid));
getPdu.setType(ScopedPDU.GET);
return snmp.get(getPdu, target);
} else {
PDU getPdu = new PDU();
getPdu.add(new VariableBinding(oid));
getPdu.setType(PDU.GET);
return snmp.get(getPdu, v1target);
}
}
private UserTarget createUserTarget() {
UserTarget target = new UserTarget();
target.setAddress(nmsIP);
target.setRetries(noOfRetries);
target.setTimeout(timeOut);
target.setVersion(SnmpConstants.version3);
target.setSecurityLevel(SecurityLevel.AUTH_PRIV);
target.setSecurityName(new OctetString(securityName));
return target;
}
private CommunityTarget createUserTargetWithoutEncryption() {
CommunityTarget target = new CommunityTarget();
target.setCommunity(new OctetString("public"));
target.setAddress(nmsIP);
target.setRetries(noOfRetries);
target.setTimeout(timeOut);
target.setVersion(SnmpConstants.version1);
return target;
}
public long getTimeOut() {
return timeOut;
}
public void setTimeOut(long timeOut) {
this.timeOut = timeOut;
}
public int getNoOfRetries() {
return noOfRetries;
}
public void setNoOfRetries(int noOfRetries) {
this.noOfRetries = noOfRetries;
}
}
The execution of the program exits with
NMS IP set : **IPREMOVED**/161
UDP Protocol selected.
response null - error: nullpeerAddress: **IPREMOVED**/161source: org.snmp4j.Snmp#e580929 request: GET[{contextEngineID=80:00:1f:88:80:5e:2e:49:07:2f:68:44:57:00:00:00:00, contextName=}, requestID=588252045, errorStatus=0, errorIndex=0, VBS[1.3.6.1.2.1.1.3.0 = Null]]
Anyone has an idea what I'm doing wrong?
Edit:
From the servers syslog I can see, that the request arrives at the resource:
Jul 31 11:52:46 loadbalancer snmpd[1219]: Connection from UDP: [IP REMOVED]:54734->[IP REMOVED]:161
Jul 31 11:52:46 loadbalancer snmpd[1219]: Connection from UDP: [IP REMOVED]:54734->[IP REMOVED]:161
#i-shm I think you are doing everything ok.
The only problem in your code could be just the line in which you evaluate the response variable. Your are indicating response != null when it should be actually response == null. I mean:
import org.snmp4j.PDU;
import org.snmp4j.ScopedPDU;
import org.snmp4j.Snmp;
import org.snmp4j.Target;
import org.snmp4j.event.ResponseEvent;
import org.snmp4j.mp.SnmpConstants;
import org.snmp4j.security.AuthMD5;
import org.snmp4j.security.AuthSHA;
import org.snmp4j.security.PrivAES128;
import org.snmp4j.security.PrivDES;
import org.snmp4j.smi.OID;
import org.snmp4j.smi.VariableBinding;
public class Listener {
public static void main(String[] args) {
ServerStatusHelper agent = new ServerStatusHelper("host.tld", "udp", 161, "demo", "demo",
"pass", "pass", new AuthMD5(), new PrivDES(), true);
try {
agent.startAgent();
ResponseEvent event = agent.snmpGetOperation(SnmpConstants.sysUpTime);
final PDU response = event.getResponse();
if (response == null) {
System.out.println(
"response null - error: "+ event.getError() +
"peerAddress: " + event.getPeerAddress() +
"source: " + event.getSource().toString() +
"request: " + event.getRequest());
} else {
System.out.println("Response PDU:" + response.toString());
// Process the response as you need, maybe something like this:
long sysUpTime = response.get(0).getVariable().toLong();
// You can find relevant information in the javadocs of the library:
// https://agentpp.com/doc/snmp4j/index.html?org/snmp4j/package-summary.html
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
This is why you do not receive errors in the java code and your syslog indicates that the requests were actually sent.
I'm making an application with Google SpeechClient that has the requirements to set a GOOGLE_APPLICATION_CREDENTIALS environment variable that, once set, you can use the voice to text api.
My application is required to run in linux and windows. In linux it runs perfectly, however, on windows, when running the project, it throws an exception com.google.api.gax.rpc.UnavailableException: "io.grpc.StatusRuntimeException: UNAVAILABLE: Credentials failed to obtain metadata" when trying to run this thread
package Controller.Runnables;
import Controller.GUI.VoxSpeechGUIController;
import Model.SpokenTextHistory;
import com.google.api.gax.rpc.ClientStream;
import com.google.api.gax.rpc.ResponseObserver;
import com.google.api.gax.rpc.StreamController;
import com.google.cloud.speech.v1.*;
import com.google.protobuf.ByteString;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.TargetDataLine;
import java.io.IOException;
import java.util.ArrayList;
public class SpeechRecognizerRunnable implements Runnable{
private VoxSpeechGUIController controller;
public SpeechRecognizerRunnable(VoxSpeechGUIController voxSpeechGUIController) {
this.controller = voxSpeechGUIController;
}
#Override
public void run() {
MicrofoneRunnable micrunnable = MicrofoneRunnable.getInstance();
Thread micThread = new Thread(micrunnable);
ResponseObserver<StreamingRecognizeResponse> responseObserver = null;
try (SpeechClient client = SpeechClient.create()) {
ClientStream<StreamingRecognizeRequest> clientStream;
responseObserver =
new ResponseObserver<StreamingRecognizeResponse>() {
ArrayList<StreamingRecognizeResponse> responses = new ArrayList<>();
public void onStart(StreamController controller) {}
public void onResponse(StreamingRecognizeResponse response) {
try {
responses.add(response);
StreamingRecognitionResult result = response.getResultsList().get(0);
// There can be several alternative transcripts for a given chunk of speech. Just
// use the first (most likely) one here.
SpeechRecognitionAlternative alternative = result.getAlternativesList().get(0);
String transcript = alternative.getTranscript();
System.out.printf("Transcript : %s\n", transcript);
String newText = SpokenTextHistory.getInstance().getActualSpeechString() + " " + transcript;
SpokenTextHistory.getInstance().setActualSpeechString(newText);
controller.setLabelText(newText);
}
catch (Exception ex){
System.out.println(ex.getMessage());
ex.printStackTrace();
}
}
public void onComplete() {
}
public void onError(Throwable t) {
System.out.println(t);
}
};
clientStream = client.streamingRecognizeCallable().splitCall(responseObserver);
RecognitionConfig recognitionConfig =
RecognitionConfig.newBuilder()
.setEncoding(RecognitionConfig.AudioEncoding.LINEAR16)
.setLanguageCode("pt-BR")
.setSampleRateHertz(16000)
.build();
StreamingRecognitionConfig streamingRecognitionConfig =
StreamingRecognitionConfig.newBuilder().setConfig(recognitionConfig).build();
StreamingRecognizeRequest request =
StreamingRecognizeRequest.newBuilder()
.setStreamingConfig(streamingRecognitionConfig)
.build(); // The first request in a streaming call has to be a config
clientStream.send(request);
try {
// SampleRate:16000Hz, SampleSizeInBits: 16, Number of channels: 1, Signed: true,
// bigEndian: false
AudioFormat audioFormat = new AudioFormat(16000, 16, 1, true, false);
DataLine.Info targetInfo =
new DataLine.Info(
TargetDataLine.class,
audioFormat); // Set the system information to read from the microphone audio
// stream
if (!AudioSystem.isLineSupported(targetInfo)) {
System.out.println("Microphone not supported");
System.exit(0);
}
// Target data line captures the audio stream the microphone produces.
micrunnable.targetDataLine = (TargetDataLine) AudioSystem.getLine(targetInfo);
micrunnable.targetDataLine.open(audioFormat);
micThread.start();
long startTime = System.currentTimeMillis();
while (!micrunnable.stopFlag) {
long estimatedTime = System.currentTimeMillis() - startTime;
if (estimatedTime >= 55000) {
clientStream.closeSend();
clientStream = client.streamingRecognizeCallable().splitCall(responseObserver);
request =
StreamingRecognizeRequest.newBuilder()
.setStreamingConfig(streamingRecognitionConfig)
.build();
startTime = System.currentTimeMillis();
} else {
request =
StreamingRecognizeRequest.newBuilder()
.setAudioContent(ByteString.copyFrom(micrunnable.sharedQueue.take()))
.build();
}
clientStream.send(request);
}
} catch (Exception e) {
System.out.println(e);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
I've been working hard for hours and have not found a solution that solves my problem.
It is worth mentioning that the environment variable is being set correctly.
Has anyone ever had this problem with Google? What should I do to fix this?
This is my envirounment variable creator:
PS: I`ve already tried use all google alternatives to validate credentials, but all return me errors.
package Controller.Autentication;
import java.io.*;
import java.lang.reflect.Field;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
public class GoogleAuthentication {
private static final String GOOGLE_APPLICATION_CREDENTIALS = "GOOGLE_APPLICATION_CREDENTIALS";
private static final String VoxSpeechFolder = ".vox";
private static final String GoogleAuthenticationJsonFile = "VoxAuthentication.json";
public static void setupGoogleCredentials() {
String directory = defaultDirectory();
directory += File.separator+VoxSpeechFolder;
File voxPath = new File(directory);
if (!voxPath.exists()) {
voxPath.mkdirs();
}
ClassLoader classLoader = new GoogleAuthentication().getClass().getClassLoader();
File srcFile = new File(classLoader.getResource(GoogleAuthenticationJsonFile).getFile());
if(srcFile.exists()){
try {
String voxDestPath = defaultDirectory() + File.separator + VoxSpeechFolder +File.separator+ GoogleAuthenticationJsonFile;
File destFile = new File(voxDestPath);
copyFile(srcFile,destFile);
} catch (IOException e) {
e.printStackTrace();
}
}
try {
Map<String,String> googleEnv = new HashMap<>();
String path = defaultDirectory() +File.separator+ VoxSpeechFolder +File.separator+ GoogleAuthenticationJsonFile;
googleEnv.put(GOOGLE_APPLICATION_CREDENTIALS, path);
setGoogleEnv(googleEnv);
} catch (Exception e) {
e.printStackTrace();
}
}
static void copyFile(File sourceFile, File destFile)
throws IOException {
InputStream inStream ;
OutputStream outStream ;
System.out.println(destFile.getPath());
if(destFile.createNewFile()){
inStream = new FileInputStream(sourceFile);
outStream = new FileOutputStream(destFile);
byte[] buffer = new byte[1024];
int length;
while ((length = inStream.read(buffer)) > 0){
outStream.write(buffer, 0, length);
}
inStream.close();
outStream.close();
}
}
static String defaultDirectory()
{
String OS = getOperationSystem();
if (OS.contains("WIN"))
return System.getenv("APPDATA");
else if (OS.contains("MAC"))
return System.getProperty("user.home") + "/Library/Application "
+ "Support";
else if (OS.contains("LINUX")) {
return System.getProperty("user.home");
}
return System.getProperty("user.dir");
}
static String getOperationSystem() {
return System.getProperty("os.name").toUpperCase();
}
protected static void setGoogleEnv(Map<String, String> newenv) throws Exception {
try {
Class<?> processEnvironmentClass = Class.forName("java.lang.ProcessEnvironment");
Field theEnvironmentField = processEnvironmentClass.getDeclaredField("theEnvironment");
theEnvironmentField.setAccessible(true);
Map<String, String> env = (Map<String, String>) theEnvironmentField.get(null);
env.putAll(newenv);
Field theCaseInsensitiveEnvironmentField = processEnvironmentClass.getDeclaredField("theCaseInsensitiveEnvironment");
theCaseInsensitiveEnvironmentField.setAccessible(true);
Map<String, String> cienv = (Map<String, String>) theCaseInsensitiveEnvironmentField.get(null);
cienv.putAll(newenv);
} catch (NoSuchFieldException e) {
Class[] classes = Collections.class.getDeclaredClasses();
Map<String, String> env = System.getenv();
for(Class cl : classes) {
if("java.util.Collections$UnmodifiableMap".equals(cl.getName())) {
Field field = cl.getDeclaredField("m");
field.setAccessible(true);
Object obj = field.get(env);
Map<String, String> map = (Map<String, String>) obj;
map.clear();
map.putAll(newenv);
}
}
}
String genv = System.getenv(GOOGLE_APPLICATION_CREDENTIALS);
System.out.println(genv);
}
}
We're using the goole-client-api library to verify google accounts from our backend. This implementation runs on Google Cloud Platform (GCP) using App Engine and DataStore.
What we're seeing so far is for the GoogleIdTokenVerifier to work but only returns email and uid along with token signature.
The token and uid used does return all profile infos when run against our servlet but does not through our App Engine Endpoint.
Here is the code used:
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.auth.oauth2.GoogleIdToken;
import com.google.api.client.googleapis.auth.oauth2.GoogleIdTokenVerifier;
import com.google.api.client.extensions.appengine.http.UrlFetchTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Collections;
import java.util.logging.Logger;
public class GoogleVerifier implements TokenVerifier {
final Logger logger = Logger.getLogger(GoogleVerifier.class.getName());
private static GoogleVerifier instance = null;
private String privAppId;
private UrlFetchTransport httpTransport; //library required to run on GCP
private JsonFactory jsonFactory;
private GoogleVerifier() {
}
private static GoogleVerifier getInstance() {
if (instance == null) {
instance = new GoogleVerifier();
}
return instance;
}
public static void setAppId(String appId) {
getInstance().setPrivAppId(appId);
getInstance().setHttpTransport(new UrlFetchTransport());
getInstance().setJsonFactory(new JacksonFactory());
}
public static String[] verify(String token, String uid) {
return getInstance().verifyPrivate(token, uid);
}
public String[] verifyPrivate(String token, String uid) {
#SuppressWarnings("unused")
GoogleCredential credential = new GoogleCredential().setAccessToken(token);
GoogleIdTokenVerifier verifier = new GoogleIdTokenVerifier.Builder(httpTransport, jsonFactory)
.setAudience(Collections.singletonList(privAppId))
.build();
String[] payloadInfo = new String[5];
try {
GoogleIdToken idToken = verifier.verify(token);
if (idToken != null) {
GoogleIdToken.Payload payload = idToken.getPayload();
if (payload.getSubject().equals(uid)) {
logger.info("Matching google id: " + uid);
payloadInfo[0] = payload.getSubject();
payloadInfo[1] = payload.get("given_name").toString();
payloadInfo[2] = payload.get("family_name").toString();
payloadInfo[3] = payload.get("picture").toString();
payloadInfo[4] = payload.getEmail();
return payloadInfo;
} else {
logger.info("Mismatching google id: " + uid);
return payloadInfo;
}
}
}
catch (Exception e) {
e.printStackTrace();
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
logger.warning(sw.toString());
return payloadInfo;
}
return payloadInfo;
}
private void setPrivAppId(String appId) {
this.privAppId = appId;
}
private void setHttpTransport(UrlFetchTransport httpTransport) {
this.httpTransport = httpTransport;
}
private void setJsonFactory(JsonFactory jsonFactory) {
this.jsonFactory = jsonFactory;
}
}
Here is our App Engine Endpoint:
#ApiMethod(name = "loginSocial", path = "loginSocial", httpMethod = HttpMethod.PUT)
public Response loginSocial(#Named("token") String token,
#Named("uid") String uid,
#Named("socialWebSite") SOCIALWEBSITE socialWebSite,
HttpServletRequest request) throws DatabaseException, IOException {
Response response = new Response();
//make sure parameters and not null or empty
if (token != null && uid != null && socialWebSite != null &&
!token.trim().isEmpty() && !uid.trim().isEmpty()){
String [] userInfo = new String[5];
//validate token and retrieve info first
if (socialWebSite.equals(SOCIALWEBSITE.GOOGLE)){
GoogleVerifier.setAppId(APP_ID);
userInfo = GoogleVerifier.verify(token, uid);
}else if(socialWebSite.equals(APP_ID);
userInfo = FacebookVerifier.verify(token, uid);
}
}
}
Thanks!
I ended up using a different library which is much simpler and provided the same information.
https://stackoverflow.com/questions/22516693
I have a PNR Inquiry app on Google Play. It was working very fine. But recently Indian Railwys added captcha to their PNR Inquiry section and because of this I am not able to pass proper data to the server to get proper response. How to add this captcha in my app in form of an imageview and ask the users to enter captcha details also so that I can send proper data and get proper response.
Indian Railways PNR Inquiry Link
Here is my PnrCheck.java which I was using earlier. Please help what modifications should be done here..
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.Socket;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.Header;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.impl.DefaultHttpClientConnection;
import org.apache.http.message.BasicHttpEntityEnclosingRequest;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.BasicHttpProcessor;
import org.apache.http.protocol.ExecutionContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.HttpRequestExecutor;
import org.apache.http.protocol.RequestConnControl;
import org.apache.http.protocol.RequestContent;
import org.apache.http.protocol.RequestExpectContinue;
import org.apache.http.protocol.RequestTargetHost;
import org.apache.http.protocol.RequestUserAgent;
import org.apache.http.util.EntityUtils;
public class PNRStatusCheck {
public static void main(String args[]) {
try {
String pnr1 = "1154177041";
String reqStr = "lccp_pnrno1=" + pnr1 + "&submitpnr=Get+Status";
PNRStatusCheck check = new PNRStatusCheck();
StringBuffer data = check.getPNRResponse(reqStr, "http://www.indianrail.gov.in/cgi_bin/inet_pnrstat_cgi.cgi");
if(data != null) {
#SuppressWarnings("unused")
PNRStatus pnr = check.parseHtml(data);
}
} catch(Exception e) {
e.printStackTrace();
}
}
public StringBuffer getPNRResponse(String reqStr, String urlAddr) throws Exception {
String urlHost = null;
int port;
String method = null;
try {
URL url = new URL(urlAddr);
urlHost = url.getHost();
port = url.getPort();
method = url.getFile();
// validate port
if(port == -1) {
port = url.getDefaultPort();
}
} catch(Exception e) {
e.printStackTrace();
throw new Exception(e);
}
HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, "UTF-8");
HttpProtocolParams.setUserAgent(params, "HttpComponents/1.1");
HttpProtocolParams.setUseExpectContinue(params, true);
BasicHttpProcessor httpproc = new BasicHttpProcessor();
// Required protocol interceptors
httpproc.addInterceptor(new RequestContent());
httpproc.addInterceptor(new RequestTargetHost());
// Recommended protocol interceptors
httpproc.addInterceptor(new RequestConnControl());
httpproc.addInterceptor(new RequestUserAgent());
httpproc.addInterceptor(new RequestExpectContinue());
HttpRequestExecutor httpexecutor = new HttpRequestExecutor();
HttpContext context = new BasicHttpContext(null);
HttpHost host = new HttpHost(urlHost, port);
DefaultHttpClientConnection conn = new DefaultHttpClientConnection();
context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, host);
#SuppressWarnings("unused")
String resData = null;
#SuppressWarnings("unused")
String statusStr = null;
StringBuffer buff = new StringBuffer();
try {
String REQ_METHOD = method;
String[] targets = { REQ_METHOD };
for (int i = 0; i < targets.length; i++) {
if (!conn.isOpen()) {
Socket socket = new Socket(host.getHostName(), host.getPort());
conn.bind(socket, params);
}
BasicHttpEntityEnclosingRequest req = new BasicHttpEntityEnclosingRequest("POST", targets[i]);
req.setEntity(new InputStreamEntity(new ByteArrayInputStream(reqStr.toString().getBytes()), reqStr.length()));
req.setHeader("Content-Type", "application/x-www-form-urlencoded");
req.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/535.7 (KHTML, like Gecko) Chrome/16.0.912.75 Safari/535.7");
req.setHeader("Cache-Control", "max-age=0");
req.setHeader("Connection", "keep-alive");
req.setHeader("Origin", "http://www.indianrail.gov.in");
req.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
req.setHeader("Referer", "http://www.indianrail.gov.in/pnr_Enq.html");
//req.setHeader("Accept-Encoding", "gzip,deflate,sdch");
req.setHeader("Accept-Language", "en-US,en;q=0.8");
req.setHeader("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.3");
httpexecutor.preProcess(req, httpproc, context);
HttpResponse response = httpexecutor.execute(req, conn, context);
response.setParams(params);
httpexecutor.postProcess(response, httpproc, context);
Header[] headers = response.getAllHeaders();
for(int j=0; j<headers.length; j++) {
if(headers[j].getName().equalsIgnoreCase("ERROR_MSG")) {
resData = EntityUtils.toString(response.getEntity());
}
}
statusStr = response.getStatusLine().toString();
InputStream in = response.getEntity().getContent();
BufferedReader reader = null;
if(in != null) {
reader = new BufferedReader(new InputStreamReader(in));
}
String line = null;
while((line = reader.readLine()) != null) {
buff.append(line + "\n");
}
try {
in.close();
} catch (Exception e) {}
}
} catch (Exception e) {
throw new Exception(e);
} finally {
try {
conn.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return buff;
}
public PNRStatus parseHtml(StringBuffer data) throws Exception {
BufferedReader reader = null;
if(data != null) {
reader = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(data.toString().getBytes())));
} else {
return null;
}
String line = null;
TrainDetails trainDetails = new TrainDetails();
List<PassengerDetails> passDetailsList = new ArrayList<PassengerDetails>();
PassengerDetails passDetails = null;
int i = 0;
while ((line = reader.readLine()) != null) {
if(line.startsWith("<TD") && line.contains("table_border_both")) {
line = line.replace("<B>", "");
line = line.substring(line.indexOf("\">")+2, line.indexOf("</")).trim();
if(line.contains("CHART")) {
trainDetails.setChatStatus(line);
break;
}
if(i > 7) {//Passenger Details
if(passDetails == null) {
passDetails = new PassengerDetails();
}
switch(i) {
case 8 :
passDetails.setName(line);
break;
case 9 :
passDetails.setBookingStatus(line.replace(" ", ""));
break;
case 10 :
passDetails.setCurrentStatus(line.replace(" ", ""));
i = 7;
break;
}
if(i == 7 ) {
passDetailsList.add(passDetails);
passDetails = null;
}
} else { // Train details
switch(i){
case 0 :
trainDetails.setNumber(line);
break;
case 1 :
trainDetails.setName(line);
break;
case 2 :
trainDetails.setBoardingDate(line);
break;
case 3 :
trainDetails.setFrom(line);
break;
case 4 :
trainDetails.setTo(line);
break;
case 5 :
trainDetails.setReservedUpto(line);
break;
case 6 :
trainDetails.setBoardingPoint(line);
break;
case 7 :
trainDetails.setReservedType(line);
break;
default :
break;
}
}
i++;
}
}
if(trainDetails.getNumber() != null) {
PNRStatus pnrStatus = new PNRStatus();
pnrStatus.setTrainDetails(trainDetails);
pnrStatus.setPassengerDetails(passDetailsList);
return pnrStatus;
} else {
return null;
}
}
}
If you right click on that page and see the source on http://www.indianrail.gov.in/pnr_Enq.html, you'll find the source of function that generates the captcha, compare the captcha and validates it:
There is a javascript function hat draws the captcha:
//Generates the captcha function that draws the captcha
function DrawCaptcha()
{
var a = Math.ceil(Math.random() * 9)+ '';
var b = Math.ceil(Math.random() * 9)+ '';
var c = Math.ceil(Math.random() * 9)+ '';
var d = Math.ceil(Math.random() * 9)+ '';
var e = Math.ceil(Math.random() * 9)+ '';
var code = a + b + c + d + e;
document.getElementById("txtCaptcha").value = code;
document.getElementById("txtCaptchaDiv").innerHTML = code;
}
//Function to checking the form inputs:
function checkform(theform){
var why = "";
if(theform.txtInput.value == ""){
why += "- Security code should not be empty.\n";
}
if(theform.txtInput.value != ""){
if(ValidCaptcha(theform.txtInput.value) == false){ //here validating the captcha
why += "- Security code did not match.\n";
}
}
if(why != ""){
alert(why);
return false;
}
}
// Validate the Entered input aganist the generated security code function
function ValidCaptcha(){
var str1 = removeSpaces(document.getElementById('txtCaptcha').value);
var str2 = removeSpaces(document.getElementById('txtInput').value);
if (str1 == str2){
return true;
}else{
return false;
}
}
// Remove the spaces from the entered and generated code
function removeSpaces(string){
return string.split(' ').join('');
}
Also instead of using URL http://www.indianrail.gov.in/cgi_bin/inet_pnrstat_cgi.cgi, try URL: http://www.indianrail.gov.in/cgi_bin/inet_pnstat_cgi_28688.cgi . The previous one is down. I think it has been changed.
Hope this helps you.
I found this answer on one post asking same:
If you check the html code, its actualy pretty bad captcha. Background of captcha is: http://www.indianrail.gov.in/1.jpg Those numbers are actualy in input tag:
What they are doing is, via javascript, use numbers from that hidden input tag and put them on that span with "captcha" background.
So basicaly your flow is:
read their html
get "captcha" (lol, funny captcha though) value from input field
when user puts data in your PNR field and presses Get Status
post form field, put PNR in proper value, put captcha in proper value
parse response
Oh yeah, one more thing. You can put any value in hidden input and "captcha" input, as long as they are the same. They aren't checking it via session or anything.
EDIT (code sample for submiting form): To simplify posting form i recommend HttpClient components from Apache: http://hc.apache.org/downloads.cgi Lets say you downloaded HttpClient 4.3.1. Include client, core and mime libraries in your project (copy to libs folder, right click on project, properties, Java Build Path, Libraries, Add Jars -> add those 3.).
Code example would be:
private static final String FORM_TARGET = "http://www.indianrail.gov.in/cgi_bin/inet_pnstat_cgi.cgi";
private static final String INPUT_PNR = "lccp_pnrno1";
private static final String INPUT_CAPTCHA = "lccp_capinp_val";
private static final String INPUT_CAPTCHA_HIDDEN = "lccp_cap_val";
private void getHtml(String userPnr) {
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addTextBody(INPUT_PNR, userPnr); // users PNR code
builder.addTextBody(INPUT_CAPTCHA, "123456");
builder.addTextBody("submit", "Get Status");
builder.addTextBody(INPUT_CAPTCHA_HIDDEN, "123456"); // values don't
// matter as
// long as they
// are the same
HttpEntity entity = builder.build();
HttpPost httpPost = new HttpPost(FORM_TARGET);
httpPost.setEntity(entity);
HttpClient client = new DefaultHttpClient();
HttpResponse response = null;
String htmlString = "";
try {
response = client.execute(httpPost);
htmlString = convertStreamToString(response.getEntity().getContent());
// now you can parse this string to get data you require.
} catch (Exception letsIgnoreItForNow) {
}
}
private static String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line);
}
} catch (IOException ignoredOnceMore) {
} finally {
try {
is.close();
} catch (IOException manyIgnoredExceptions) {
}
}
return sb.toString();
}
Also, be warned i didn't wrap this in AsyncTask call, so you will have to do that.
package com.intel.bluetooth.javadoc.ServicesSearch;
import java.io.IOException;
import java.io.OutputStream;
import javax.microedition.io.Connector;
import javax.obex.*;
//import java.util.Vector;
public class ObexPutClient {
public static void main(String[] args) throws IOException, InterruptedException {
String serverURL = null; // = "btgoep://0019639C4007:6";
if ((args != null) && (args.length > 0)) {
serverURL = args[0];
}
if (serverURL == null) {
String[] searchArgs = null;
// Connect to OBEXPutServer from examples
// searchArgs = new String[] { "11111111111111111111111111111123" };
**ServicesSearch**.main(searchArgs);
if (ServicesSearch.serviceFound.size() == 0) {
System.out.println("OBEX service not found");
return;
}
// Select the first service found
serverURL = (String)ServicesSearch.serviceFound.elementAt(0);
}
System.out.println("Connecting to " + serverURL);
ClientSession clientSession = (ClientSession) Connector.open(serverURL);
HeaderSet hsConnectReply = clientSession.connect(null);
if (hsConnectReply.getResponseCode() != ResponseCodes.OBEX_HTTP_OK) {
System.out.println("Failed to connect");
return;
}
HeaderSet hsOperation = clientSession.createHeaderSet();
hsOperation.setHeader(HeaderSet.NAME, "Hello.txt");
hsOperation.setHeader(HeaderSet.TYPE, "text");
//Create PUT Operation
Operation putOperation = clientSession.put(hsOperation);
// Send some text to server
byte data[] = "Hello world!".getBytes("iso-8859-1");
OutputStream os = putOperation.openOutputStream();
os.write(data);
os.close();
putOperation.close();
clientSession.disconnect(null);
clientSession.close();
}
}
Can anyone help me?The error is in bold letters.
Thank You
Do you have ServicesSearch created? Or included? and imported (in case it exists in some other package).
Show us the code, and tell us more.