401:Authentication credentials were invalid - Invalid or expired token. code - 89 - twitter

This is the code and I am recieving the error 401: Authentication Error
public class Server {
// initialize socket and input stream
private Socket socket = null;
private ServerSocket server = null;
private DataInputStream in = null;
public void tweet() throws TwitterException {
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDaemonEnabled(true).setOAuthConsumerKey("......")
.setOAuthConsumerSecret("......")
.setOAuthAccessToken("......")
.setOAuthAccessTokenSecret(".....");
TwitterFactory tf = new TwitterFactory();
twitter4j.Twitter twitter = tf.getInstance();
List status = twitter.getHomeTimeline();
for (Status st : status) {
System.out.println(st.getUser().getName() + "---- Tweets----" + st.getText());
}
}
// constructor with port
public Server(int port) throws TwitterException {
// starts server and waits for a connection
try {
server = new ServerSocket(port);
System.out.println("Server started");
System.out.println("Waiting for a client ...");
socket = server.accept();
System.out.println("Client accepted");
// takes input from the client socket
in = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
String line = "";
// reads message from client until "Over" is sent
while (!line.equals("Over")) {
try {
line = in.readUTF();
System.out.println(line);
if (line.equalsIgnoreCase("Data")) {
tweet();
}
} catch (IOException i) {
System.out.println(i);
}
}
System.out.println("Closing connection");
// close connection
socket.close();
in.close();
} catch (IOException i) {
System.out.println(i);
}
}
public static void main(String args[]) throws TwitterException {
Server server = new Server(5000);
}
}

Please make sure that the tokens are valid.
Then, you could try enabling system proxies like so:
System.setProperty("java.net.useSystemProxies", "true");

Related

AWS transcribe Unable to load credentials from any of the providers in the chain AwsCredentialsProviderChain

I am running a java program that uses AWS TranscribeStreaming. I have created(from AWS console) and downloaded AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY then set the environment variables.
When I run the program I am getting error message:
Unable to load credentials from any of the providers in the chain AwsCredentialsProviderChain.
I don't why but this error was also occurring while using Google SDK for speech recognition.
here is the code I am trying to run.
public class TranscribeStreamingDemoApp {
private static final Region REGION = Region.US_WEST_2;
private static TranscribeStreamingAsyncClient client;
public static void main(String args[]) throws URISyntaxException, ExecutionException, InterruptedException, LineUnavailableException {
client = TranscribeStreamingAsyncClient.builder()
.credentialsProvider(getCredentials())
.region(REGION)
.build();
CompletableFuture<Void> result = client.startStreamTranscription(getRequest(16_000),
new AudioStreamPublisher(getStreamFromMic()),
getResponseHandler());
result.get();
client.close();
}
private static InputStream getStreamFromMic() throws LineUnavailableException {
// Signed PCM AudioFormat with 16kHz, 16 bit sample size, mono
int sampleRate = 16000;
AudioFormat format = new AudioFormat(sampleRate, 16, 1, true, false);
DataLine.Info info = new DataLine.Info(TargetDataLine.class, format);
if (!AudioSystem.isLineSupported(info)) {
System.out.println("Line not supported");
System.exit(0);
}
TargetDataLine line = (TargetDataLine) AudioSystem.getLine(info);
line.open(format);
line.start();
InputStream audioStream = new AudioInputStream(line);
return audioStream;
}
private static AwsCredentialsProvider getCredentials() {
return DefaultCredentialsProvider.create();
}
private static StartStreamTranscriptionRequest getRequest(Integer mediaSampleRateHertz) {
return StartStreamTranscriptionRequest.builder()
.languageCode(LanguageCode.FR_FR.toString())
.mediaEncoding(MediaEncoding.PCM)
.mediaSampleRateHertz(mediaSampleRateHertz)
.build();
}
private static StartStreamTranscriptionResponseHandler getResponseHandler() {
return StartStreamTranscriptionResponseHandler.builder()
.onResponse(r -> {
System.out.println("Received Initial response");
})
.onError(e -> {
System.out.println(e.getMessage());
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
System.out.println("Error Occurred: " + sw.toString());
})
.onComplete(() -> {
System.out.println("=== All records stream successfully ===");
})
.subscriber(event -> {
List<software.amazon.awssdk.services.transcribestreaming.model.Result> results = ((TranscriptEvent) event).transcript().results();
if (results.size() > 0) {
if (!results.get(0).alternatives().get(0).transcript().isEmpty()) {
System.out.println(results.get(0).alternatives().get(0).transcript());
}
}
})
.build();
}
private InputStream getStreamFromFile(String audioFileName) {
try {
File inputFile = new File(getClass().getClassLoader().getResource(audioFileName).getFile());
InputStream audioStream = new FileInputStream(inputFile);
return audioStream;
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
}
}
private static class AudioStreamPublisher implements Publisher<AudioStream> {
private final InputStream inputStream;
private static Subscription currentSubscription;
private AudioStreamPublisher(InputStream inputStream) {
this.inputStream = inputStream;
}
#Override
public void subscribe(Subscriber<? super AudioStream> s) {
if (this.currentSubscription == null) {
this.currentSubscription = new SubscriptionImpl(s, inputStream);
} else {
this.currentSubscription.cancel();
this.currentSubscription = new SubscriptionImpl(s, inputStream);
}
s.onSubscribe(currentSubscription);
}
}
public static class SubscriptionImpl implements Subscription {
private static final int CHUNK_SIZE_IN_BYTES = 1024 * 1;
private final Subscriber<? super AudioStream> subscriber;
private final InputStream inputStream;
private ExecutorService executor = Executors.newFixedThreadPool(1);
private AtomicLong demand = new AtomicLong(0);
SubscriptionImpl(Subscriber<? super AudioStream> s, InputStream inputStream) {
this.subscriber = s;
this.inputStream = inputStream;
}
#Override
public void request(long n) {
if (n <= 0) {
subscriber.onError(new IllegalArgumentException("Demand must be positive"));
}
demand.getAndAdd(n);
executor.submit(() -> {
try {
do {
ByteBuffer audioBuffer = getNextEvent();
if (audioBuffer.remaining() > 0) {
AudioEvent audioEvent = audioEventFromBuffer(audioBuffer);
subscriber.onNext(audioEvent);
} else {
subscriber.onComplete();
break;
}
} while (demand.decrementAndGet() > 0);
} catch (Exception e) {
subscriber.onError(e);
}
});
}
#Override
public void cancel() {
executor.shutdown();
}
private ByteBuffer getNextEvent() {
ByteBuffer audioBuffer = null;
byte[] audioBytes = new byte[CHUNK_SIZE_IN_BYTES];
int len = 0;
try {
len = inputStream.read(audioBytes);
if (len <= 0) {
audioBuffer = ByteBuffer.allocate(0);
} else {
audioBuffer = ByteBuffer.wrap(audioBytes, 0, len);
}
} catch (IOException e) {
throw new UncheckedIOException(e);
}
return audioBuffer;
}
private AudioEvent audioEventFromBuffer(ByteBuffer bb) {
return AudioEvent.builder()
.audioChunk(SdkBytes.fromByteBuffer(bb))
.build();
}
}
}
Finally, I solved the problem, the documentation specifies that:
AWS credentials provider chain that looks for credentials in this order:
1.Java System Properties - aws.accessKeyId and aws.secretAccessKey
2.Environment Variables - AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY
3.Credential profiles file at the default location (~/.aws/credentials) shared by all AWS SDKs and the AWS CLI
Since setting up through environment variables didn't work, I opted to set credentials with Java system properties and it works!
Doc ref: https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/auth/credentials/DefaultCredentialsProvider.html
System.setProperty("aws.accessKeyId", "**************");
System.setProperty("aws.secretAccessKey", "**************");

Fetch parameters from redirected url in OAuth2 in java

I need to use OAuth 2.0 for accessing user's data.
I have used glassfish security oauth 2 library to implement OAuth 2 client.
I am not sure how can I get code and state values after user granted permission to access the data.
ClientIdentifier clientIdentifier = new ClientIdentifier(clientId, secret);
OAuth2CodeGrantFlow.Builder builder =
OAuth2ClientSupport.authorizationCodeGrantFlowBuilder(clientIdentifier,
HOST_NAME + "/authorize",
HOST_NAME + "/token");
OAuth2CodeGrantFlow flow = builder
.scope("activity")
.redirectUri("http://example.com/#/")
.build();
String authorizationUri = flow.start();
System.out.println(authorizationUri);
String redirectedUrl = getFinalRedirectedUrl(authorizationUri);
System.out.print("Enter the authorization code: ");
String code = "";
String state = "";
try {
code = IN.readLine();
state = IN.readLine();
} catch (final IOException ex) {
throw new RuntimeException(ex);
}
final TokenResult result = flow.finish(code, state);
System.out.println("Access Token: " + result.getAllProperties());
}
For Now, I am taking code and status manually from the redirected url. How Can I automate it.
I tried
public static String getFinalRedirectedUrl(String url) {
String finalRedirectedUrl = url;
try {
HttpURLConnection connection;
do {
connection = (HttpURLConnection) new URL(finalRedirectedUrl).openConnection();
connection.setInstanceFollowRedirects(false);
connection.setUseCaches(false);
connection.setRequestMethod("GET");
connection.connect();
int responseCode = connection.getResponseCode();
if (responseCode >= 300 && responseCode < 400) {
String redirectedUrl = connection.getHeaderField("Location");
if (null == redirectedUrl) {
break;
}
finalRedirectedUrl = redirectedUrl;
} else
break;
} while (connection.getResponseCode() != HttpURLConnection.HTTP_OK);
connection.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(finalRedirectedUrl);
return finalRedirectedUrl;
}
but it returns the login page.

Smack 4.1 connection to gtalk

I updated to smack 4.1, but now cannot connect to gtalk. This is my code I am using:
XMPPTCPConnectionConfiguration.Builder configBuilder = XMPPTCPConnectionConfiguration.builder();
configBuilder.setHost("talk.google.com");
configBuilder.setPort(5222);
configBuilder.setServiceName("gmail.com");
configBuilder.setSecurityMode(SecurityMode.required);
configBuilder.setDebuggerEnabled(true);
configBuilder.setSendPresence(true);
configBuilder.setUsernameAndPassword(pref.getString(Constants.KEY_USER, ""), pref.getString(Constants.KEY_TOKEN, ""));
SASLAuthentication.blacklistSASLMechanism(SASLMechanism.PLAIN);
AbstractXMPPConnection connection = new XMPPTCPConnection(configBuilder.build());
try
{
connection.connect();
connection.login();//.login(pref.getString(Constants.KEY_USER, ""), pref.getString(Constants.KEY_TOKEN, ""));
}
catch(Exception e)
{
e.printStackTrace();
return null;
}
This is the error i get:
D/SMACK(12807): SENT (3): <auth xmlns='urn:ietf:params:xml:ns:xmpp-sasl' mechanism='X-OAUTH2'>REMOVED_THIS=</auth>
D/SMACK(12807): RECV (3): <failure xmlns="urn:ietf:params:xml:ns:xmpp-sasl"><incorrect-encoding/></failure>
The problem is the line in SASLXOauth2Mechanism:
Base64.encode(toBytes('\u0000' + authenticationId + '\u0000' + password));
As a quick test replace in your code
AbstractXMPPConnection connection = new XMPPTCPConnection(configBuilder.build());
with this
AbstractXMPPConnection connection = new XMPPTCPConnection(configBuilder.build())
{
#Override
public void send(PlainStreamElement auth) throws NotConnectedException
{
if(auth instanceof AuthMechanism)
{
final XmlStringBuilder xml = new XmlStringBuilder();
xml.halfOpenElement(AuthMechanism.ELEMENT)
.xmlnsAttribute(SaslStreamElements.NAMESPACE)
.attribute("mechanism", "X-OAUTH2")
.attribute("auth:service", "oauth2")
.attribute("xmlns:auth", "http://www.google.com/talk/protocol/auth")
.rightAngleBracket()
.optAppend(Base64.encodeToString(StringUtils.toBytes("\0" + authenticationId + "\0" + password)))
.closeElement(AuthMechanism.ELEMENT);
super.send(new PlainStreamElement()
{
#Override
public String toXML()
{
return xml.toString();
}
});
}
else super.send(auth);
}
};
I didn't test it, but I hope it works. authenticationId and token are your credentials.

Enabling Multiple Connection Type

I have a HTTP Connection on my application, for the current time being it is only applicable if the users are connected to WIFI connection. How would I do this if I'd like to enable it for any connections that the particular device has? Say that the device has a BIS service, or even a normal WAP service.
This is my code.
try
{
connection = (HttpConnection) Connector.open(url+ ";interface=wifi");
is = connection.openInputStream();
try
{
SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
parser.parse(is, rssHandler);
}
catch (ParserConfigurationException e)
{
e.printStackTrace();
}
catch (SAXException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
catch (IOException e)
{
e.printStackTrace();
Dialog.inform("Bad URL");
}
Use the following code to get the connection string
/**
* Determines what connection type to use and returns the necessary string to use it.
* #return A string with the connection info
*/
private static String getConnectionString()
{
// This code is based on the connection code developed by Mike Nelson of AccelGolf.
// http://blog.accelgolf.com/2009/05/22/blackberry-cross-carrier-and-cross-network-http-connection
String connectionString = null;
// Simulator behavior is controlled by the USE_MDS_IN_SIMULATOR variable.
if(DeviceInfo.isSimulator())
{
if(UploaderThread.USE_MDS_IN_SIMULATOR)
{
logMessage("Device is a simulator and USE_MDS_IN_SIMULATOR is true");
connectionString = ";deviceside=false";
}
else
{
logMessage("Device is a simulator and USE_MDS_IN_SIMULATOR is false");
connectionString = ";deviceside=true";
}
}
// Wifi is the preferred transmission method
else if(WLANInfo.getWLANState() == WLANInfo.WLAN_STATE_CONNECTED)
{
logMessage("Device is connected via Wifi.");
connectionString = ";interface=wifi";
}
// Is the carrier network the only way to connect?
else if((CoverageInfo.getCoverageStatus() & CoverageInfo.COVERAGE_DIRECT) == CoverageInfo.COVERAGE_DIRECT)
{
logMessage("Carrier coverage.");
String carrierUid = getCarrierBIBSUid();
if(carrierUid == null)
{
// Has carrier coverage, but not BIBS. So use the carrier's TCP network
logMessage("No Uid");
connectionString = ";deviceside=true";
}
else
{
// otherwise, use the Uid to construct a valid carrier BIBS request
logMessage("uid is: " + carrierUid);
connectionString = ";deviceside=false;connectionUID="+carrierUid + ";ConnectionType=mds-public";
}
}
// Check for an MDS connection instead (BlackBerry Enterprise Server)
else if((CoverageInfo.getCoverageStatus() & CoverageInfo.COVERAGE_MDS) == CoverageInfo.COVERAGE_MDS)
{
logMessage("MDS coverage found");
connectionString = ";deviceside=false";
}
// If there is no connection available abort to avoid bugging the user unnecssarily.
else if(CoverageInfo.getCoverageStatus() == CoverageInfo.COVERAGE_NONE)
{
logMessage("There is no available connection.");
}
// In theory, all bases are covered so this shouldn't be reachable.
else
{
logMessage("no other options found, assuming device.");
connectionString = ";deviceside=true";
}
return connectionString;
}
/**
* Looks through the phone's service book for a carrier provided BIBS network
* #return The uid used to connect to that network.
*/
private static String getCarrierBIBSUid()
{
ServiceRecord[] records = ServiceBook.getSB().getRecords();
int currentRecord;
for(currentRecord = 0; currentRecord < records.length; currentRecord++) { if(records[currentRecord].getCid().toLowerCase().equals("ippp")) { if(records[currentRecord].getName().toLowerCase().indexOf("bibs") >= 0)
{
return records[currentRecord].getUid();
}
}
}
return null;
}

Critical Tunnel failure exception. How to solve this

I wrote the below code to send location coordinates to server:
setTitle("version 5.0");
Criteria criteria = new Criteria();
criteria.setHorizontalAccuracy(Criteria.NO_REQUIREMENT);
criteria.setVerticalAccuracy(Criteria.NO_REQUIREMENT);
criteria.setCostAllowed(true);
criteria.setPreferredPowerConsumption(Criteria.POWER_USAGE_LOW);
// bc.setFailoverMode(GPSInfo.GPS_MODE_ssCDMA_MS_ASSIST, 2, 100);
try {
LocationProvider lp=LocationProvider.getInstance(criteria);
if(lp !=null)
{
Location loc=null;
// while(loc==null)
// {
loc=lp.getLocation(-1);
// }
if(loc!=null){
add(new EditField(loc.getQualifiedCoordinates().getLatitude()+"\n"+loc.getQualifiedCoordinates().getLongitude(),""));
}
else
add(new EditField("unable to find the location provider", ""));
}
else
{
add(new EditField("unable to find the location provider", ""));
}
} catch (LocationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ButtonField b = new ButtonField("Send");
add(b);
b.setChangeListener(new FieldChangeListener() {
public void fieldChanged(Field field, int context) {
// TODO Auto-generated method stub
try{
String url="http://56.91.532.72:8084/SFTS/updateLocation.jsp?empid=12304&lat=16.9477&lon=82.23970;deviceside=true";
Dialog.alert(url);
ConnectionFactory factory = new ConnectionFactory();
// use the factory to get a connection
ConnectionDescriptor conDescriptor = factory.getConnection(url, TransportInfo.TRANSPORT_TCP_CELLULAR,null);
if ( conDescriptor != null ) {
HttpConnection conn = (HttpConnection) conDescriptor.getConnection();
Dialog.alert("http");
//conn.setRequestMethod(HttpConnection.GET);
Dialog.alert("conn.setre");
int responseCode = conn.getResponseCode();
Dialog.alert(Integer.toString(responseCode));
if(responseCode == HttpConnection.HTTP_OK)
{
Dialog.alert("OK");
InputStream data = conn.openInputStream();
StringBuffer raw = new StringBuffer();
byte[] buf = new byte[4096];
int nRead = data.read(buf);
while(nRead > 0)
{
raw.append(new String(buf, 0, nRead));
nRead = data.read(buf);
}
}
}
}catch(Exception e){
Dialog.alert(e.getMessage());
}
}
});
I am getting an exception Critical tunnel failure. But i am able to retrieve the location coordinates correctly. I am using blackberry 8520 with airtel sim which is enabled with data services. Actually this app worked well in the mobile with version 5.0. But it's not working in the mobile which i've upgraded from 4.6.1.3 to 5.0.0 what might be the problem? Please provide me a solution. thank you
I also tried the below url's:
http://56.91.532.72:8084/SFTS/updateLocation.jsp?empid=12304&lat=16.9477&lon=82.23970;deviceside=true;apn=null
http://56.91.532.72:8084/SFTS/updateLocation.jsp?empid=12304&lat=16.9477&lon=82.23970;deviceside=true;apn=airtelgprs.com
I also enabled apn settings in my mobile
It is because you haven't set up the apn correctly. As you are using direct tcp, the apn has to be set in order to connect to the network.
Also , network connections should be done on a separate thread.

Resources