Calling HTTP API Using Java to send SMS - java

I have attached my HTTP Class now i need to make a call to this class when ever i need to send my SMS on button click. I seem not to find any solution. Any help would be deeply appreciated.
public class Sender {
// Username that is to be used for submission
String username;
// password that is to be used along with username
String password;
// Message content that is to be transmitted
String message;
/**
* What type of the message that is to be sent
* <ul>
* <li>0:means plain text</li>
* <li>1:means flash</li>
* <li>2:means Unicode (Message content should be in Hex)</li>
* <li>6:means Unicode Flash (Message content should be in Hex)</li>
* </ul>
*/
String type;
/**
* Require DLR or not
* <ul>
* <li>0:means DLR is not Required</li>
* <li>1:means DLR is Required</li>
* </ul>
*/
String dlr;
/**
* Destinations to which message is to be sent For submitting more than one
* destination at once destinations should be comma separated Like
* 91999000123,91999000124
*/
String destination;
// Sender Id to be used for submitting the message
String source;
// To what server you need to connect to for submission
String server;
// Port that is to be used like 8080 or 8000
int port;
public Sender(String server, int port, String username, String password,
String message, String dlr, String type, String destination,
String source) {
this.username = username;
this.password = password;
this.message = message;
this.dlr = dlr;
this.type = type;
this.destination = destination;
this.source = source;
this.server = server;
this.port = port;
}
private void submitMessage() {
try {
// Url that will be called to submit the message
URL sendUrl = new URL("http://" + this.server + ":" + this.port
+ "/bulksms/bulksms");
HttpURLConnection httpConnection = (HttpURLConnection) sendUrl
.openConnection();
// This method sets the method type to POST so that
// will be send as a POST request
httpConnection.setRequestMethod("POST");
// This method is set as true wince we intend to send
// input to the server
httpConnection.setDoInput(true);
// This method implies that we intend to receive data from server httpConnection.setDoOutput(true);
// Implies do not use cached data
httpConnection.setUseCaches(false);
// Data that will be sent over the stream to the server.
DataOutputStream dataStreamToServer = new DataOutputStream(
httpConnection.getOutputStream());
dataStreamToServer.writeBytes("username="
+ URLEncoder.encode(this.username, "UTF-8") + "&password="
+ URLEncoder.encode(this.password, "UTF-8") + "&type="
+ URLEncoder.encode(this.type, "UTF-8") + "&dlr="
+ URLEncoder.encode(this.dlr, "UTF-8") + "&destination="
+ URLEncoder.encode(this.destination, "UTF-8") + "&source="
+ URLEncoder.encode(this.source, "UTF-8") + "&message="
+ URLEncoder.encode(this.message, "UTF-8"));
dataStreamToServer.flush();
dataStreamToServer.close();
// Here take the output value of the server.
BufferedReader dataStreamFromUrl = new BufferedReader(
new InputStreamReader(httpConnection.getInputStream()));
String dataFromUrl = "", dataBuffer = "";
// Writing information from the stream to the buffer
while ((dataBuffer = dataStreamFromUrl.readLine()) != null) {
dataFromUrl += dataBuffer;
}
/**
* Now dataFromUrl variable contains the Response received from the
* server so we can parse the response and process it accordingly.
*/
dataStreamFromUrl.close();
System.out.println("Response: " + dataFromUrl);
} catch (Exception ex) {
ex.printStackTrace();
}
}
public void main(String[] args) {
try {
// Below exmaple is for sending Plain text
Sender s = new Sender("http:", 8080, "xxxxxxx",
"xxxxx", "Congratulations! You just gave someone a priceless gift - LIFE! Thank you for donating." +
"Your next donation date is 13/6/16. Get ", "1", "0", "xxxxxxx",
"xxxx");
s.submitMessage();
// Below exmaple is for sending unicode
Sender s1 = new Sender("smpp2.routesms.com", 8080, "xxxx",
"xxx", convertToUnicode("test for unicode").toString(),
"1", "2", "919869533416", "Update");
s1.submitMessage();
} catch (Exception ex) {
}
}
/**
* Below method converts the unicode to hex value
* #param regText
* #return
*/
private StringBuffer convertToUnicode(String regText) {
char[] chars = regText.toCharArray();
StringBuffer hexString = new StringBuffer();
for (int i = 0; i < chars.length; i++) {
String iniHexString = Integer.toHexString((int) chars[i]);
if (iniHexString.length() == 1) {
iniHexString = "000" + iniHexString;
}
else if (iniHexString.length() == 2)
iniHexString = "00" + iniHexString;
else if (iniHexString.length() == 3)
iniHexString = "0" + iniHexString;
hexString.append(iniHexString);
}
System.out.println(hexString);
return hexString;
}
}
I cant seem to call this class from Android app to send sms via the sms APi i have attached.
I have attached my call to the sender class to make a call to the http class when i want to send an SMS on button click.
Button button;
button = (Button) findViewById(R.id.noBtn);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//createUserAppointment();
Sender sender = new Sender("xxxxxxxxxxxxx", 8080, "xxxxx",
"xxxx", "Congratulations! You just gave someone a priceless gift - LIFE! Thank you for donating." +
"Your next donation date is 13/6/16.", "1", "0", "xxxxxxxxx",
"Moja");
sender.submitMessage();
}
});

And what produces your attempt? An error? Or it compiles well but does'nt do anything? Please share any output too
Well you put "xxxxxxxxx" in args because you don't want us to see the real adress or because you are just copy pasting the example?
Otherwise I'd suggest you to take a look here
I am trying http connection over android

Related

How to get all the queues and topics from solace

I want to discover all the destinations from solace (queues and topics)
I tried using MBeanServerConnection and query after names (but I didn't find a proper way to use this) or JNDI lookups Destination dest = (Destination) context.lookup(Dest_name), but I don't have the names of the queues/topics.
I am using solace - jms library.
I am searching for smth like this: (but for solace, not activeMq)
get all Queue from activeMQ
You will need to make use of SEMP over the management interface for this.
Sample commands:
curl -d '<rpc><show><queue><name>*</name></queue></show></rpc>' -u semp_username:semp_password http://your_management_ip:your_management_port/SEMP
curl -d '<rpc><show><topic-endpoint><name>*</name></topic-endpoint></show></rpc>' -u semp_username:semp_password http://your_management_ip:your_management_port/SEMP
Note that I'm using curl for simplicity, but any application can perform HTTP POSTs to execute these commands.
If you are using Java, you can refer to the SempHttpSetRequest sample found within the Solace API samples.
Documentation on SEMP can be found here.
However, the larger question here is why do you need to discover all destinations?
One of the features of the message broker is to decouple the publishers and consumers.
If you need to know if your persistent message is being published to a topic with no consumers, you can make use of the reject-msg-to-sender-on-no-subscription-match setting in the publishing application's client-profile.
This means that the publisher will obtain a negative acknowledgement in the event that it tries to publish a message on a topic that has no matching subscribers.
You can refer to "Handling Guaranteed Messages with No Matches" at https://docs.solace.com/Configuring-and-Managing/Configuring-Client-Profiles.htm for further details.
Here is some source code that might help. With the appliance configured correctly, SEMP is also available over JMS on topic "#SEMP/(router)/SHOW".
/**
* Return the SolTopicInfo for this topic (or all topics if 'topic' is null).
*
* #param session
* #param endpointName
* #return
*/
public static SolTopicInfo[] getTopicInfo(JCSMPSession session, String endpointName, String vpn,
String sempVersion) {
XMLMessageConsumer cons = null;
XMLMessageProducer prod = null;
Map<String, SolTopicInfo> tiMap = new HashMap<String, SolTopicInfo>();
try {
// Create a producer and a consumer, and connect to appliance.
prod = session.getMessageProducer(new PubCallback());
cons = session.getMessageConsumer(new SubCallback());
cons.start();
if (vpn == null) vpn = (String) session.getProperty(JCSMPProperties.VPN_NAME);
if (sempVersion == null) sempVersion = getSempVersion(session);
// Extract the router name.
final String SEMP_SHOW_TE_TOPICS = "<rpc semp-version=\""
+ sempVersion
+ "\"><show><topic-endpoint><name>"
+ endpointName
+ "</name><vpn-name>"+ vpn + "</vpn-name></topic-endpoint></show></rpc>";
RpcReply teTopics = sendRequest(session, SEMP_SHOW_TE_TOPICS);
for (TopicEndpoint2 te : teTopics.getRpc().getShow().getTopicEndpoint().getTopicEndpoints()
.getTopicEndpointArray()) {
SolTopicInfo ti = new SolTopicInfo();
ti.setBindCount(te.getInfo().getBindCount());
//qi.setDescription(qt.getInfo().getNetworkTopic());
ti.setEndpoint(te.getName());
ti.setMessageVPN(te.getInfo().getMessageVpn());
ti.setTopic(te.getInfo().getDestination());
ti.setDurable(te.getInfo().getDurable());
ti.setInSelPres(te.getInfo().getIngressSelectorPresent());
ti.setHwmMB(formatter.format(te.getInfo().getHighWaterMarkInMb()));
ti.setSpoolUsageMB(formatter.format(te.getInfo().getCurrentSpoolUsageInMb()));
ti.setMessagesSpooled(te.getInfo().getNumMessagesSpooled().longValue());
String status = te.getInfo().getIngressConfigStatus().substring(0, 1).toUpperCase();
status += " " + te.getInfo().getEgressConfigStatus().substring(0, 1).toUpperCase();
status += " " + te.getInfo().getIngressSelectorPresent().substring(0, 1).toUpperCase();
status += " " + te.getInfo().getType().substring(0, 1).toUpperCase();
ti.setStatus(status);
tiMap.put(ti.getEndpoint(), ti);
}
} catch (JCSMPException e) {
throw new RuntimeException(e.getMessage(), e);
} finally {
if (cons != null)
cons.close();
if (prod != null)
prod.close();
}
return tiMap.values().toArray(new SolTopicInfo[0]);
}
/**
* Return the SolQueueInfo for this queue (or all queues if 'queue' is null).
*
* #param session
* #param queue
* #param vpn (if null, use the session's vpn name)
* #param sempVersion, if null use 'soltr/7_1_1'
* #return
*/
public static SolQueueInfo[] getQueueInfo(JCSMPSession session, String queue, String vpn,
String sempVersion) {
XMLMessageConsumer cons = null;
XMLMessageProducer prod = null;
Map<String, SolQueueInfo> qiMap = new HashMap<String, SolQueueInfo>();
try {
// Create a producer and a consumer, and connect to appliance.
prod = session.getMessageProducer(new PubCallback());
cons = session.getMessageConsumer(new SubCallback());
cons.start();
if (vpn == null) vpn = (String) session.getProperty(JCSMPProperties.VPN_NAME);
if (sempVersion == null) sempVersion = getSempVersion(session);
// Extract the router name.
final String SEMP_SHOW_QUEUE_SUBS = "<rpc semp-version=\""
+ sempVersion
+ "\"><show><queue><name>"
+ queue
+ "</name><vpn-name>"+ vpn + "</vpn-name><subscriptions/><count/><num-elements>200</num-elements></queue></show></rpc>";
RpcReply queueSubs = sendRequest(session, SEMP_SHOW_QUEUE_SUBS);
for (QueueType qt : queueSubs.getRpc().getShow().getQueue().getQueues().getQueueArray()) {
SolQueueInfo qi = new SolQueueInfo();
qi.setBindCount(qt.getInfo().getBindCount());
//qi.setDescription(qt.getInfo().getNetworkTopic());
qi.setName(qt.getName());
qi.setMessageVPN(qt.getInfo().getMessageVpn());
qi.setDurable(qt.getInfo().getDurable());
qi.setEgSelPres(qt.getInfo().getEgressSelectorPresent());
qi.setHwmMB(formatter.format(qt.getInfo().getHighWaterMarkInMb()));
qi.setMessagesSpooled(qt.getInfo().getNumMessagesSpooled().longValue());
qi.setSpoolUsageMB(formatter.format(qt.getInfo().getCurrentSpoolUsageInMb()));
String status = qt.getInfo().getIngressConfigStatus().substring(0, 1).toUpperCase();
status += " " + qt.getInfo().getEgressConfigStatus().substring(0, 1).toUpperCase();
status += " " + qt.getInfo().getAccessType().substring(0, 1).toUpperCase();
status += " " + qt.getInfo().getEgressSelectorPresent().substring(0, 1).toUpperCase();
status += " " + qt.getInfo().getType().substring(0, 1).toUpperCase();
status += qt.getInfo().getDurable() ? " D" : " N";
qi.setStatus(status);
for (Subscription sub : qt.getSubscriptions().getSubscriptionArray()) {
qi.addSubscription(sub.getTopic());
}
qiMap.put(qi.getName(), qi);
}
} catch (JCSMPException e) {
throw new RuntimeException(e.getMessage(), e);
} finally {
if (cons != null)
cons.close();
if (prod != null)
prod.close();
}
return qiMap.values().toArray(new SolQueueInfo[0]);
}
private static String getSempVersion(JCSMPSession session)
{
String retval = "soltr/7_1_1";
try {
String peerVersion = (String)session.getCapability(CapabilityType.PEER_SOFTWARE_VERSION);
if (peerVersion != null)
{
retval = "soltr/";
String[] version = peerVersion.split("\\.");
retval += version[0];
retval += "_" + version[1];
if (!version[2].equals("0")) retval += "_" + version[2];
}
} catch (Throwable e) {
System.err.println(e);
}
return retval;
}
private static RpcReply sendRequest(JCSMPSession session,
final String requestStr) {
try {
// Set up the requestor and request message.
String routerName = (String) session
.getCapability(CapabilityType.PEER_ROUTER_NAME);
final String SEMP_TOPIC_STRING = String.format("#SEMP/%s/SHOW",
routerName);
final Topic SEMP_TOPIC = JCSMPFactory.onlyInstance().createTopic(
SEMP_TOPIC_STRING);
Requestor requestor = session.createRequestor();
BytesXMLMessage requestMsg = JCSMPFactory.onlyInstance().createMessage(
BytesXMLMessage.class);
requestMsg.writeAttachment(requestStr.getBytes());
BytesXMLMessage replyMsg = requestor
.request(requestMsg, 5000, SEMP_TOPIC);
String replyStr = new String();
if (replyMsg.getAttachmentContentLength() > 0) {
byte[] bytes = new byte[replyMsg.getAttachmentContentLength()];
replyMsg.readAttachmentBytes(bytes);
replyStr = new String(bytes, "US-ASCII");
}
RpcReplyDocument doc = RpcReplyDocument.Factory.parse(replyStr);
RpcReply reply = doc.getRpcReply();
if (reply.isSetPermissionError()) {
throw new RuntimeException(
"Permission Error: Make sure SEMP over message bus SHOW commands are enabled for this VPN");
}
if( reply.isSetParseError() ) {
throw new RuntimeException( "SEMP Parse Error: " + reply.getParseError() );
}
if( reply.isSetLimitError() ) {
throw new RuntimeException( "SEMP Limit Error: " + reply.getLimitError() );
}
if( reply.isSetExecuteResult() && reply.getExecuteResult().isSetReason() ) { // axelp: encountered this error on invalid 'queue' name
throw new RuntimeException( "SEMP Execution Error: " + reply.getExecuteResult().getReason() );
}
return reply;
} catch (JCSMPException e) {
throw new RuntimeException(e.getMessage(), e);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e.getMessage(), e);
} catch (XmlException e) {
throw new RuntimeException(e.getMessage(), e);
}
}
You can get message VPN specific queues and topics using following SEMPv2 command.
curl -s -X GET -u semp_user:semp_pass management_host:management_port/SEMP/v2/monitor/msgVpns/{vpn-name}/queues?select="queueName"
curl -s -X GET -u semp_user:semp_pass management_host:management_port/SEMP/v2/monitor/msgVpns/{vpn-name}/topicEndpoints?select="topicEndpointName"

Is restFB generated token is genuine?

I working with restFB for calling FaceBook Graph api to login, get posts and etc of users.
Created an app in developers account of Facebook.
Tried to call user details, with token generated here,
https://developers.facebook.com/tools/explorer?method=GET&path=8560751784547897&version=v2.8
For Example: accessToken from the above url provides = EAA....F
I am able to get all user details, when I am hitting url in browser as follows,
https://graph.facebook.com/v2.8/me?fields=id,name,email,birthday?access_token=EAA....f
I am getting following response in browser,
{
"id": "1127949",
"name": "youtr name",
"email": "youmail\u0040gmail.com"
"birthday": "10/27/1998"
}
I used following code to generate accesstoken dynamically,
StringBuffer callbackURLbuffer = request.getRequestURL();
int index = callbackURLbuffer.lastIndexOf("/");
callbackURLbuffer.replace(index, callbackURLbuffer.length(), "").append("/callback");
callbackURL = URLEncoder.encode(callbackURLbuffer.toString(), "UTF-8");
String authURL = "https://graph.facebook.com/oauth/authorize?client_id="
+ facebookAppId
+ "&redirect_uri="
+ callbackURL
+ "&scope=user_about_me,"
+ "user_actions.books,user_actions.fitness,user_actions.music,user_actions.news,user_actions.video,user_activities,user_birthday,user_education_history,"
+ "user_events,user_photos,user_friends,user_games_activity,user_groups,user_hometown,user_interests,user_likes,user_location,user_photos,user_relationship_details,"
+ "user_relationships,user_religion_politics,user_status,user_tagged_places,user_videos,user_website,user_work_history,ads_management,ads_read,email,"
+ "manage_notifications,manage_pages,publish_actions,read_friendlists,read_insights,read_mailbox,read_page_mailboxes,read_stream,rsvp_event";
In my callbackURL servlet, I am getting accessToken with code value, as follows,
StringBuffer redirectURLbuffer = request.getRequestURL();
int index = redirectURLbuffer.lastIndexOf("/");
redirectURLbuffer.replace(index, redirectURLbuffer.length(), "").append("/callback");
redirectURL = URLEncoder.encode(redirectURLbuffer.toString(), "UTF-8");
code = request.getParameter("code");
if(null!=code) {
accessURL = "https://graph.facebook.com/oauth/access_token?client_id=" + facebookAppId +
"&redirect_uri=" + redirectURL + "&client_secret=" + facebookAppSecret + "&code=" + code;
webContent = getWebContentFromURL(accessURL);
accessToken = getAccessTokenFromWebContent(webContent);
other functions used for this above code,
private static String getWebContentFromURL(String webnames) {
try {
URL url = new URL(webnames);
URLConnection urlc = url.openConnection();
//BufferedInputStream buffer = new BufferedInputStream(urlc.getInputStream());
BufferedReader buffer = new BufferedReader(new InputStreamReader(urlc.getInputStream(), "UTF8"));
StringBuffer builder = new StringBuffer();
int byteRead;
while ((byteRead = buffer.read()) != -1)
builder.append((char) byteRead);
buffer.close();
String text=builder.toString();
return text;
}
catch (IOException e) {
e.printStackTrace();
}
return null;
}
And,
private static String getAccessTokenFromWebContent (String webContent) {
String accessToken = null;
int s = webContent.indexOf("access_token=") + ("access_token=".length());
int e = webContent.indexOf("&");
accessToken = webContent.substring(s, e);
return accessToken;
}
Lets say this accessToken = EAA....2
If I call the below url with this Token,
https://graph.facebook.com/v2.8/me?fields=id,name,email,birthday&access_token=EAA....2
I am getting following response,
{
"id": "1127949",
"name": "youtr name",
"email": "youmail\u0040gmail.com"
}
If I hit following url, with bio feild, I got error msg in json as follows,
{
"error": {
"message": "(#12) bio field is deprecated for versions v2.8 and higher",
"type": "OAuthException",
"code": 12,
"fbtrace_id": "ARkoFJVP/Jk"
}
}
can some one say why this is happening for me.
Take a look here, to get about the user permission.
https://developers.facebook.com/docs/facebook-login/permissions/#reference-user_about_me.
As per your comment, regarding debuggin your token, sounds like you didn't get the permission enabled for user_about_me by facebook.
You have to send Facebook for a review about your app and need to approve by Facebook, then only you can access the user details and other things.
Follow these steps,
Go to - https://developers.facebook.com/apps/your_app_id/review-status/
Click on Start a submission button.
Select the check boxes,which you needs for permission. Then Click add Items button.
Then click on Edit Notes for each permission.
Here, breif about your app with this permission and upload a video of demo of your app.
Facebook will review it and accept/reject as per the norms.
This is what you are missing and it causes for your problem..

Gridsim: Extend functionality in network flow

I'm working on gridsim project in Java eclipse. I have found a network flow program, which works only for one-to-one connection between the sender and receiver. If the same user (sender) wish to send a message to any other receiver, the program does not work. Similarly, if a receiver wish to send message to two sender users, it does not work. Here, I'm including all the java files for this work. In order to run the program, we need to include external .jar file path in the project. The gridsim.jar and simjava2.jar files can be downloaded from http://sourceforge.net/projects/gridsim/
The following are the programs. The main program is FlowNetEx01.java
package network.flow.example01;
import gridsim.*;
import gridsim.net.*;
import gridsim.net.flow.*;
import java.util.*;
// Test Driver class for this example
public class FlowNetEx01
{
// Creates main() to run this example
public static void main(String[] args)
{
System.out.println("Starting network example ...");
try
{
int num_user = 4; // number of grid users
Calendar calendar = Calendar.getInstance();
boolean trace_flag = false; // mean trace GridSim events
System.out.println("Initializing GridSim package");
// It is essential to set the network type before calling GridSim.init()
GridSim.initNetworkType(GridSimTags.NET_FLOW_LEVEL);
GridSim.init(num_user, calendar, trace_flag);
// In this example, the topology is:
// user(s) --10Mb/s-- r1 --1.5Mb/s-- r2 --10Mb/s-- GridResource(s)
Router r1 = new FlowRouter("router1", trace_flag); // router 1
Router r2 = new FlowRouter("router2", trace_flag); // router 2
String sender1 = "user1";
String receipient1 = "test1";
String sender2 = "user2";
String receipient2 = "test2";
// these entities are the senders
FlowNetUser user1 = new FlowNetUser(sender1, receipient2, 5.0);
FlowNetUser user2 = new FlowNetUser(sender2, receipient1, 20.0);
// these entities are the receipients
FlowTest test1 = new FlowTest(receipient1, sender2);
FlowTest test2 = new FlowTest(receipient2, sender1);
// The schedulers are redundent and will be stripped out soon
FIFOScheduler userSched1 = new FIFOScheduler("NetUserSched_0");
r1.attachHost(user1, userSched1);
FIFOScheduler userSched2 = new FIFOScheduler("NetUserSched_1");
r1.attachHost(user2, userSched2);
FIFOScheduler testSched1 = new FIFOScheduler("FlowTestSched_0");
r2.attachHost(test1, testSched1);
FIFOScheduler testSched2 = new FIFOScheduler("FlowTestSched_1");
r2.attachHost(test2, testSched2);
//////////////////////////////////////////
// Second step: Creates a physical link
double baud_rate = 1572864; // bits/sec (baud) [1.5Mb/s]
double propDelay = 300; // propagation delay in millisecond
int mtu = Integer.MAX_VALUE;; // max. transmission unit in byte
Link link = new FlowLink("r1_r2_link", baud_rate, propDelay, mtu);
FIFOScheduler r1Sched = new FIFOScheduler("r1_Sched");
FIFOScheduler r2Sched = new FIFOScheduler("r2_Sched");
r1.attachRouter(r2, link, r1Sched, r2Sched);
//////////////////////////////////////////
// Final step: Starts the simulation
GridSim.startGridSimulation();
System.out.println("\nFinish network example ...");
}
catch (Exception e)
{
e.printStackTrace();
System.err.print(e.toString());
System.out.println("Unwanted errors happen");
}
}
} // end class
Program-2:
package network.flow.example01;
import gridsim.*;
import gridsim.net.*;
import gridsim.net.flow.*;
import eduni.simjava.*;
import java.util.*;
public class FlowNetUser extends GridSim
{
private int myID_; // my entity ID
private String name_; // my entity name
private String destName_; // destination name
private int destID_; // destination id
private double wait_; // Delay until I begin sending
public static final int SEND_MSG = 1;
public static final int ACK_MSG = 2;
public FlowNetUser(String name, String destName, Link link, double wait) throws Exception
{
super(name, link);
// get this entity name from Sim_entity
this.name_ = super.get_name();
// get this entity ID from Sim_entity
this.myID_ = super.get_id();
// get the destination entity name
this.destName_ = destName;
// get the waiting time before sending
this.wait_ = wait;
}
public FlowNetUser(String name, String destName, double wait) throws Exception
{
// 10,485,760 baud = 10Mb/s
super(name, new FlowLink(name+"_link",10485760,450,Integer.MAX_VALUE));
// get this entity name from Sim_entity
this.name_ = super.get_name();
// get this entity ID from Sim_entity
this.myID_ = super.get_id();
// get the destination entity name
destName_ = destName;
// get the waiting time before sending
this.wait_ = wait;
}
public void body()
{
int packetSize = 524288000; // packet size in bytes [5MB]
//int packetSize = 52428800; // packet size in bytes [50MB]
//int packetSize = 524288000; // packet size in bytes [500MB]
//int packetSize = 5242880000; // packet size in bytes [5000MB]
int size = 3; // number of packets sent
int i = 0;
// get the destination entity ID
this.destID_ = GridSim.getEntityId(destName_);
//super.sim_pause(this.wait_);
this.gridSimHold(this.wait_);
// sends messages over the other side of the link
for (i = 0; i < size; i++)
{
String msg = "Message_" + i;
IO_data data = new IO_data(msg, packetSize, destID_);
System.out.println(name_ + ".body(): Sending " + msg +
", at time = " + GridSim.clock() );
// sends through Output buffer of this entity
super.send(super.output, GridSimTags.SCHEDULE_NOW,
GridSimTags.FLOW_SUBMIT, data);
//super.sim_pause();
super.sim_pause(10.0);
//this.gridSimHold((Math.random()*10)+1.0);
}
// get the ack back
Object obj = null;
for (i = 0; i < size; i++)
{
// waiting for incoming event in the Input buffer
obj = super.receiveEventObject();
System.out.println(name_ + ".body(): Receives Ack for " + obj);
}
// Wait for other FlowNetUser instances to finish
this.gridSimHold(1000.0);
super.send(destID_, GridSimTags.SCHEDULE_NOW,
GridSimTags.END_OF_SIMULATION);
// shut down I/O ports
shutdownUserEntity();
terminateIOEntities();
System.out.println(this.name_ + ":%%%% Exiting body() at time " +
GridSim.clock() );
}
} // end class
Program-3:
package network.flow.example01;
import java.util.*;
import gridsim.*;
import gridsim.net.*;
import gridsim.net.flow.*;
import gridsim.util.SimReport;
import eduni.simjava.*;
public class FlowTest extends GridSim
{
private int myID_; // my entity ID
private String name_; // my entity name
private String destName_; // destination name
private int destID_; // destination id
private SimReport report_; // logs every activity
public FlowTest(String name, String destName, Link link) throws Exception
{
super(name, link);
// get this entity name from Sim_entity
this.name_ = super.get_name();
// get this entity ID from Sim_entity
this.myID_ = super.get_id();
// get the destination entity name
this.destName_ = destName;
// logs every activity. It will automatically create name.csv file
report_ = new SimReport(name);
report_.write("Creates " + name);
}
public FlowTest(String name, String destName) throws Exception
{
// 10,485,760 baud = 10Mb/s
super(name, new FlowLink(name+"_link",10485760,250,Integer.MAX_VALUE));
// get this entity name from Sim_entity
this.name_ = super.get_name();
// get this entity ID from Sim_entity
this.myID_ = super.get_id();
// get the destination entity name
this.destName_ = destName;
// logs every activity. It will automatically create name.csv file
report_ = new SimReport(name);
report_.write("Creates " + name);
}
public void body()
{
// get the destination entity ID
this.destID_ = GridSim.getEntityId(destName_);
int packetSize = 1500; // packet size in bytes
Sim_event ev = new Sim_event(); // an event
// a loop waiting for incoming events
while ( Sim_system.running() )
{
// get the next event from the Input buffer
super.sim_get_next(ev);
// if an event denotes end of simulation
if (ev.get_tag() == GridSimTags.END_OF_SIMULATION)
{
System.out.println();
write(super.get_name() + ".body(): exiting ...");
break;
}
// if an event denotes another event type
else if (ev.get_tag() == GridSimTags.FLOW_SUBMIT)
{
System.out.println();
write(super.get_name() + ".body(): receive " +
ev.get_data() + ", at time = " + GridSim.clock());
// No need for an ack, it is handled in FlowBuffer now on our behalf
// sends back an ack
IO_data data = new IO_data(ev.get_data(), packetSize, destID_);
write(name_ + ".body(): Sending back " +
ev.get_data() + ", at time = " + GridSim.clock() );
// sends through Output buffer of this entity
super.send(super.output, GridSimTags.SCHEDULE_NOW,
GridSimTags.FLOW_ACK, data);
}
else if (ev.get_tag() == GridSimTags.INFOPKT_SUBMIT)
{
processPingRequest(ev);
}
}
// shut down I/O ports
shutdownUserEntity();
terminateIOEntities();
// don't forget to close the file
if (report_ != null) {
report_.finalWrite();
}
System.out.println(this.name_ + ":%%%% Exiting body() at time " +
GridSim.clock() );
}
private void processPingRequest(Sim_event ev)
{
InfoPacket pkt = (InfoPacket) ev.get_data();
pkt.setTag(GridSimTags.INFOPKT_RETURN);
pkt.setDestID( pkt.getSrcID() );
// sends back to the sender
super.send(super.output, GridSimTags.SCHEDULE_NOW,
GridSimTags.INFOPKT_RETURN,
new IO_data(pkt,pkt.getSize(),pkt.getSrcID()) );
}
private void write(String msg)
{
System.out.println(msg);
if (report_ != null) {
report_.write(msg);
}
}
} // end class
After running these programs, someone can tell us how to extend the required functionality as I mentioned in the beginning.
Personal experience ... GridSim5.2 potentially buggy.
The examples are dated written for version < 4.0, demonstrating not very complex scenarios.
Using version 5.2. According to the API docs every simulation should have at least one TopRegionalRC. This appends a UniqueID to the filename and records the location of the file in two hashmaps one for filename and the other for fileattr. Now the event filename used for the lookup remains unchanged - the lookup fails - compares to the fileattrmap.name_. Consequently, the waiting for ack block is never executed when performing a addmaster operation.
Fix: Since the UniqueId is returned by the initial request to the CTLG this can be appended to the filename for the subsequent event requiring the lookup. Alternatively, add the filename to fileattrmap and the filename+uniqueid to fileattrmap, then test for both in the lookup.
Also, GridSimTags uses -1 to signal END_OF_SIMULATION, but this conflicts with Advanced Reservation (AR) block of tags. That also use negative numbers. GridSimTags has an optional routine to check for duplicates but its use is optional and does not apply to DataGridTags. I created a reversemap for ease of debugging adding validation to ensure no duplicates occur and deprecated the GridSimTags method.
I am now wrestling with the DataGrid user tasks that do not seem to create events, I am also concerned that the delay operations are not effective.

how do you get the ticket_id on vimeo api with scribe

I am trying to upload video to vimeo and I understand that you need the ticket_id in order to be able to upload.
The think is I can not figure out how to get this ticket_id by using scribe.
Does anyone have any example how to do this?
Thanks in advance.
When I use:
OAuthRequest request = new OAuthRequest(Verb.GET, "http://vimeo.com/api/rest/v2");
request.addQuerystringParameter("method", "vimeo.videos.upload.getTicket");
this results in:
<err code="401" expl="The consumer key passed was not valid." msg="Invalid consumer key"/>
When I use method:
request.addQuerystringParameter("method", "vimeo.videos.upload.getQuota");
everything works fine. I tried putting some fake api key in the vimeo.videos.upload.getQuota method. That also resulted in invalid key. So it is not like method vimeo.videos.upload.getQuota does not need the api key. In fact it does and if you don't provide the valid key it wil not work. Somehow when calling method vimeo.videos.upload.getTicket, with the same api key that works for the mehod getQuota, I get response:
<err code="401" expl="The consumer key passed was not valid." msg="Invalid consumer key"/>
full code with fake api keys:
public class VimeoServiceConcept {
public static void main(String[] args) {
String apikey="api key";
String apisecret="secret";
String accessToken="access token";
String accessTokenSecret="access token secret";
OAuthService service = new ServiceBuilder()
.provider(VimeoApi.class)
.apiKey(apikey)
.apiSecret(apisecret)
.build();
Token token = new Token(accessToken, accessTokenSecret);
OAuthRequest request = new OAuthRequest(Verb.GET, "http://vimeo.com/api/rest/v2");
// request.addQuerystringParameter("method", "vimeo.videos.upload.getQuota");
request.addQuerystringParameter("format", "xml");
request.addQuerystringParameter("method", "vimeo.videos.upload.getTicket");
request.addQuerystringParameter("upload_method", "post");
service.signRequest(token, request);
System.out.println(request.getCompleteUrl());
Response response = request.send();
System.out.println("Got it! Lets see what we found...");
System.out.println(response.getHeader("code"));
System.out.println(response.getCode());
System.out.println(response.getBody());
}
}
Try getting the ticket after you get the quota. I have never tried getting the ticket without the quota first because their documentation explicitly states you need to check quota before you get the ticket. It looks like you just comment out what you're not testing. Try this instead:
public class VimeoServiceConcept {
public static void main(String[] args) {
String apikey="api key";
String apisecret="secret";
String accessToken="access token";
String accessTokenSecret="access token secret";
OAuthService service = new ServiceBuilder().provider(VimeoApi.class).apiKey(apiKey).apiSecret(apiSecret).build();
OAuthRequest request;
Response response;
accessToken = new Token("your_token", "your_tokens_secret");
accessToken = checkToken(vimeoAPIURL, accessToken, service);
if (accessToken == null) {
return;
}
// Get Quota
request = new OAuthRequest(Verb.GET, vimeoAPIURL);
request.addQuerystringParameter("method", "vimeo.videos.upload.getQuota");
signAndSendToVimeo(request, "getQuota", true);
// Get Ticket
request = new OAuthRequest(Verb.GET, vimeoAPIURL);
request.addQuerystringParameter("method", "vimeo.videos.upload.getTicket");
request.addQuerystringParameter("upload_method", "streaming");
response = signAndSendToVimeo(request, "getTicket", true);
//... the rest of your code...
}
}
Here's checkToken:
/**
* Checks the token to make sure it's still valid. If not, it pops up a dialog asking the user to
* authenticate.
*/
private static Token checkToken(String vimeoAPIURL, Token vimeoToken, OAuthService vimeoService) {
if (vimeoToken == null) {
vimeoToken = getNewToken(vimeoService);
} else {
OAuthRequest request = new OAuthRequest(Verb.GET, vimeoAPIURL);
request.addQuerystringParameter("method", "vimeo.oauth.checkAccessToken");
Response response = signAndSendToVimeo(request, "checkAccessToken", true);
if (response.isSuccessful()
&& (response.getCode() != 200 || response.getBody().contains("<err code=\"302\"")
|| response.getBody().contains("<err code=\"401\""))) {
vimeoToken = getNewToken(vimeoService);
}
}
return vimeoToken;
}
Here's getNewToken:
/**
* Gets authorization URL, pops up a dialog asking the user to authenticate with the url and the user
* returns the authorization code
*
* #param service
* #return
*/
private static Token getNewToken(OAuthService service) {
// Obtain the Authorization URL
Token requestToken = service.getRequestToken();
String authorizationUrl = service.getAuthorizationUrl(requestToken);
do {
String code = JOptionPane.showInputDialog("The token for the account (whatever)" + newline
+ "is either not set or is no longer valid." + newline
+ "Please go to the URL below and authorize this application." + newline
+ "Paste the code you're given on top of the URL here and click \'OK\'" + newline
+ "(click the 'x' or input the letter 'q' to cancel." + newline
+ "If you input an invalid code, I'll keep popping up).", authorizationUrl + "&permission=delete");
if (code == null) {
return null;
}
Verifier verifier = new Verifier(code);
// Trade the Request Token and Verfier for the Access Token
System.out.println("Trading the Request Token for an Access Token...");
try {
Token token = service.getAccessToken(requestToken, verifier);
System.out.println(token); //Use this output to copy the token into your code so you don't have to do this over and over.
return token;
} catch (OAuthException ex) {
int choice = JOptionPane.showConfirmDialog(null, "There was an OAuthException" + newline
+ ex + newline
+ "Would you like to try again?", "OAuthException", JOptionPane.YES_NO_OPTION);
if (choice == JOptionPane.NO_OPTION) {
break;
}
}
} while (true);
return null;
}
Here's signAndSend:
/**
* Signs the request and sends it. Returns the response.
*
* #param request
* #return response
*/
public static Response signAndSendToVimeo(OAuthRequest request, String description, boolean printBody) throws org.scribe.exceptions.OAuthException {
System.out.println(newline + newline
+ "Signing " + description + " request:"
+ ((printBody && !request.getBodyContents().isEmpty()) ? newline + "\tBody Contents:" + request.getBodyContents() : "")
+ ((!request.getHeaders().isEmpty()) ? newline + "\tHeaders: " + request.getHeaders() : ""));
service.signRequest(accessToken, request);
printRequest(request, description);
Response response = request.send();
printResponse(response, description, printBody);
return response;
}

Digest authentication with Jersey Client

I have written a REST web service with Jersey Server (that totally rocks !).
I am now developing the client part of it, with Jersey Client as well.
On the server side, I have chosen a DIGEST authentication, because I personally think that BASIC authentication is an heresy that should be marked as "DEPRECATED" in our heads.
Unfortunately, I do not see any support of the Digest authentication on the client side.
For BASIC authentication, one does something like :
client.addFilter(
new HTTPBasicAuthFilter(
user,
password));
But I see no "HTTPDigestAuthFilter" counterpart.
Am I missing something ?
Thanks for your help,
Raphael
I have just implemented it.
I have created a feature request in the Jersey issue tracker, and posted my implementation there, as attachment :
https://jersey.dev.java.net/issues/show_bug.cgi?id=542
It works fine for communicating with a DIGEST authentication of a Tomcat server.
I have not tested for other web servers yet.
Here I wrote some random uri. Please fill your desired URI
For sample testing you can take help of google services which are available in the internet for open.
import javax.ws.rs.core.*;
import org.apache.commons.codec.digest.*;
import org.codehaus.jettison.json.*;
import com.sun.jersey.api.*;
public class DigestClient {
//Dividing into two parts because we need to send the last part of uri in our second request to service.
static String baseUri = "https://www.something.com";
static String subUri = "/later-part";
public static void main(String[] args) throws JSONException{
ClientConfig cc = new DefaultClientConfig();
Client client = Client.create(cc);
WebResource webResource = client.resource(baseUri+subUri);
ClientResponse response = webResource.get(ClientResponse.class);
// Basically in Digest-Authentication mechanism, we hit the rest service two times.
// First time with No Authentication, which returns some values (qop, nonce, realm) which are used as inputs in second call to rest service.
/*--------------- First call-----------------*/
// We get 401, Unauthorized
System.out.println(response.getStatus()+" "+response.getStatusInfo());
// Here is the complete header information
System.out.println(response.getHeaders());
// We need "WWW-Authenticate" part information for our second call to rest
System.out.println("WWW-Authenticate: \t" + response.getHeaders().get("www-Authenticate"));
String noAuthResp = response.getHeaders().get("www-Authenticate").toString();
noAuthResp = noAuthResp.replace("Digest ", "");
noAuthResp = noAuthResp.replace('[', '{');
noAuthResp = noAuthResp.replace(']', '}');
// Creating a JSONObject for easy information retrieval
JSONObject resp = new JSONObject(noAuthResp);
/*--------------- Second call-----------------*/
// Here client has to set the fields which was returned from the first call
String user = "postman"; // username
String password = "password"; // password
String realm = resp.getString("realm"); // realm value from the first rest-call response
String qop = resp.getString("qop"); //qop value from the first rest-call response
String nonce = resp.getString("nonce"); // nonce value from the first rest-call response
String opaque = resp.getString("opaque"); // Some times if we don't get this value, set it with ""
String algorithm = "MD5"; // The algorithm set by the client
int nonceCount = 678; // Some numerical input from the client
String clientNonce = "afdjas0"; // Some random text from the client for encryption
String method = "GET"; // HTTP method
String ha1 = new DigestClient().formHA1(user, realm, password);
String ha2 = new DigestClient().formHA2(method, subUri);
String responseCode = new DigestClient().generateResponse(ha1, nonce, nonceCount, clientNonce, qop, ha2);
// Header to be sent to the service
String value = "Digest username=\""+user+"\", realm=\""+realm+"\", nonce=\""+nonce+"\", uri=\""+subUri+"\", qop="+qop+", nc="+nonceCount+", cnonce=\""+clientNonce+"\", response=\""+responseCode+"\", opaque=\""+opaque+"\"";
// Hitting the service
response = webResource.header("authorization", value).type(MediaType.TEXT_PLAIN).accept("*").get(ClientResponse.class);
System.out.println("\nComplete Response:\n"+response+"\n");
String output = response.getEntity(String.class);
System.out.println("Response Text: "+output);
}
// For generating HA1 value
public String formHA1(String userName,String realm,String password){
String ha1 = DigestUtils.md5Hex(userName + ":" + realm + ":" + password);
return ha1;
}
// For generating HA2 value
public String formHA2(String method,String uri){
String ha2=DigestUtils.md5Hex(method + ":" + uri);
return ha2;
}
// For generating response at client side
public String generateResponse(String ha1,String nonce,int nonceCount,String clientNonce,String qop,String ha2){
String response=DigestUtils.md5Hex(ha1 + ":" + nonce + ":" + nonceCount + ":" +clientNonce +":" + qop + ":" +ha2);
return response;
}
}

Categories