Json String Deserilize - java

I called eFinans e-Archive service. faturaOlustur method expects me a json string. I created an variable and assing json string value and giving input parameter. Input parameter expects me String. But variable side expects me only string. I can't solve a solution that problem. Please examine and give me a clue please.
public static void eArsivConnectorClient(){
String username = "username";
String password = "password";
String endPointUrl = "https://earsivtest.efinans.com.tr:443/earsiv/ws/EarsivWebService";
try{
EarsivWebService_Service earsivService = new EarsivWebService_Service(new URL (endPointUrl + "?wsdl"));
earsivService.setHandlerResolver(new SoapHandlerResolver(username, password));
EarsivWebService earsivPort = earsivService.getEarsivWebServicePort();
WSBindingProvider bindingProvider = (WSBindingProvider) earsivPort;
bindingProvider.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, endPointUrl);
try
{
EarsivServiceResult srvResult = new EarsivServiceResult();
Holder<Belge> output = null;
String[] input = new String[]{"vkn","4250566851", "sube","DFLT1", "kasa","DFLT1",
"islemId","12232", "erpKodu","ERP1"};**
Belge fatura = new Belge();
fatura.setBelgeFormati(BelgeFormatiEnum.UBL);
Path path = Paths.get("C:\\RNK2022000002605.xml");
byte[] value = Files.readAllBytes(path);
fatura.setBelgeIcerigi(value);
EarsivServiceResult arsivBelge = earsivPort.faturaOlustur(input, fatura , output);
System.out.println(arsivBelge.getResultCode());
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
}catch(Throwable t){
t.printStackTrace();
}
}

Related

WebServiceException: Method beaInvoke is exposed as WebMethod

Below is the code Snippet.. that must call WSDL in other server dynamically
but in the moment of calling
(int i = webServiceModuleService.notificationRecieved("xyz");)
returned exception :(
note: i haven't any beaInvoke method in my service :|
public static void main(String[] args) {
java.sql.Connection conn = null;
InitialContext context;
try {
context = new InitialContext();
DataSource ds = (DataSource) context.lookup("jdbc/dataSourceDS");
conn = ds.getConnection();
} catch (SQLException e) {
} catch (NamingException e) {
}
QueryRunner run = new QueryRunner();
SampleResultSetHandler h = new SampleResultSetHandler();
Object[] res = null;
try {
res = run.query(conn, "select SERVER_IP,SERVER_PORT from SERVER where UPPER(SERVER_NAME)=? ", h, "test");
} catch (SQLException e) {
}
String ip = res[0].toString();
String port = res[1].toString();
String endpointURL = "http://" + ip + ":" + port + "/context-root/WebServiceModuleService";
try {
URL tmpURL = new URL(endpointURL + "?wsdl");
System.err.println(tmpURL);
WebServiceModuleService_Service webServiceModuleService_Service = new WebServiceModuleService_Service(tmpURL,
new QName("/org/parsisys/test/mina/model/services/common/",
"WebServiceModuleService"));
WebServiceModuleService webServiceModuleService = null;
webServiceModuleService = webServiceModuleService_Service.getWebServiceModuleServiceSoapHttpPort();
BindingProvider bp = (BindingProvider) webServiceModuleService;
bp.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, endpointURL);
// Configure credential providers
Map<String, Object> requestContext = ((BindingProvider) webServiceModuleService).getRequestContext();
try {
setPortCredentialProviderList(requestContext);
} catch (Exception ex) {
ex.printStackTrace();
}
//Call WebService ... ==> Exception :(
int i = webServiceModuleService.notificationRecieved("xyz");
//logp("successfully call the webservice for [ip&port:" + ip + ":" + port + "] [transid : " +transid + "]");
} catch (Exception e) {
//log
//TODO: Clean This
System.err.println(e.getMessage());
e.printStackTrace();
return;
}
}
#Generated("Oracle JDeveloper")
public static void setPortCredentialProviderList(Map<String, Object> requestContext) throws Exception {
// TODO - Provide the required credential values
String username = "";
String password = "";
String clientKeyStore = "";
String clientKeyStorePassword = "";
String clientKeyAlias = "";
String clientKeyPassword = "";
String serverKeyStore = "";
String serverKeyStorePassword = "";
String serverKeyAlias = "";
List<CredentialProvider> credList = new ArrayList<CredentialProvider>();
// Add the necessary credential providers to the list
// Code commented out due to empty username/password value found in the credential.
// credList.add(getUNTCredentialProvider(username, password));
// Code commented out due to empty server keystore value found in the credential.
// credList.add(getBSTCredentialProvider(clientKeyStore, clientKeyStorePassword, clientKeyAlias, clientKeyPassword, serverKeyStore, serverKeyStorePassword, serverKeyAlias, requestContext));
credList.add(getSAMLTrustCredentialProvider());
requestContext.put(WSSecurityContext.CREDENTIAL_PROVIDER_LIST, credList);
}
#Generated("Oracle JDeveloper")
public static CredentialProvider getSAMLTrustCredentialProvider() {
return new SAMLTrustCredentialProvider();
}
daynamic webservice call is generated with jdeveloper and it's works in clien't tester but in my module when i call webservice return exception :/
StackTrace is: ↓
Method beaInvoke is exposed as WebMethod, but there is no corresponding wsdl operation with name {/org/parsisys/test/mina/model/services/common/}beaInvoke in the wsdl:portType{/org/parsisys/test/mina/model/services/common/}WebServiceModuleService
javax.xml.ws.WebServiceException: Method beaInvoke is exposed as WebMethod, but there is no corresponding wsdl operation with name {/org/parsisys/test/mina/model/services/common/}beaInvoke in the wsdl:portType{/org/parsisys/test/mina/model/services/common/}WebServiceModuleService
at com.sun.xml.ws.model.JavaMethodImpl.freeze(JavaMethodImpl.java:382)
at com.sun.xml.ws.model.AbstractSEIModelImpl.freeze(AbstractSEIModelImpl.java:124)
at com.sun.xml.ws.model.RuntimeModeler.buildRuntimeModel(RuntimeModeler.java:336)
at com.sun.xml.ws.db.DatabindingImpl.(DatabindingImpl.java:99)
at com.sun.xml.ws.db.DatabindingProviderImpl.create(DatabindingProviderImpl.java:74)
at com.sun.xml.ws.db.DatabindingProviderImpl.create(DatabindingProviderImpl.java:58)
at com.sun.xml.ws.db.DatabindingFactoryImpl.createRuntime(DatabindingFactoryImpl.java:120)
at com.sun.xml.ws.client.WSServiceDelegate.buildRuntimeModel(WSServiceDelegate.java:882)
at com.sun.xml.ws.client.WSServiceDelegate.createSEIPortInfo(WSServiceDelegate.java:899)
at com.sun.xml.ws.client.WSServiceDelegate.addSEI(WSServiceDelegate.java:862)
at com.sun.xml.ws.client.WSServiceDelegate.getPort(WSServiceDelegate.java:451)
at weblogic.wsee.jaxws.spi.WLSProvider$ServiceDelegateImpl.internalGetPort(WLSProvider.java:1698)
at weblogic.wsee.jaxws.spi.WLSProvider$ServiceDelegateImpl$PortClientInstanceFactory.createClientInstance(WLSProvider.java:1769)
at weblogic.wsee.jaxws.spi.ClientInstancePool.takeSimpleClientInstance(ClientInstancePool.java:389)
at weblogic.wsee.jaxws.spi.ClientInstancePool.take(ClientInstancePool.java:243)
at weblogic.wsee.jaxws.spi.WLSProvider$ServiceDelegateImpl$3.apply(WLSProvider.java:1555)
at weblogic.wsee.jaxws.spi.WLSProvider$ServiceDelegateImpl$3.apply(WLSProvider.java:1517)
at weblogic.wsee.jaxws.spi.ClientIdentityRegistry.initClientIdentityFeatureAndCall(ClientIdentityRegistry.java:1456)
at weblogic.wsee.jaxws.spi.WLSProvider$ServiceDelegateImpl.getPort(WLSProvider.java:1513)
at com.sun.xml.ws.client.WSServiceDelegate.getPort(WSServiceDelegate.java:420)
at weblogic.wsee.jaxws.spi.WLSProvider$ServiceDelegateImpl.getPort(WLSProvider.java:1477)
at com.sun.xml.ws.client.WSServiceDelegate.getPort(WSServiceDelegate.java:402)
at javax.xml.ws.Service.getPort(Service.java:119)
at org.parsisys.test.mina.model.service.WebServiceModuleService_Service.beaInvokeSuper(WebServiceModuleService_Service.java)
at org.parsisys.test.mina.model.service.WebServiceModuleService_Service$beaVersion0_31.getWebServiceModuleServiceSoapHttpPort(WebServiceModuleService_Service.java:51)
at org.parsisys.test.mina.model.service.WebServiceModuleService_Service.getWebServiceModuleServiceSoapHttpPort(WebServiceModuleService_Service.java)
at org.parsisys.test.mina.files.notification.queue.NotificationQueueRecieved$beaVersion0_11.onMessage(NotificationQueueRecieved.java:330)
at org.parsisys.test.mina.files.notification.queue.NotificationQueueRecieved.onMessage(NotificationQueueRecieved.java)
at weblogic.jms.client.JMSSession.onMessage(JMSSession.java:5107)
at weblogic.jms.client.JMSSession.execute(JMSSession.java:4775)
at weblogic.jms.client.JMSSession.executeMessage(JMSSession.java:4170)
at weblogic.jms.client.JMSSession.access$000(JMSSession.java:127)
at weblogic.jms.client.JMSSession$UseForRunnable.run(JMSSession.java:5627)
at weblogic.work.SelfTuningWorkManagerImpl$WorkAdapterImpl.run(SelfTuningWorkManagerImpl.java:666)
at weblogic.invocation.ComponentInvocationContextManager._runAs(ComponentInvocationContextManager.java:348)
at weblogic.invocation.ComponentInvocationContextManager.runAs(ComponentInvocationContextManager.java:333)
at weblogic.work.LivePartitionUtility.doRunWorkUnderContext(LivePartitionUtility.java:54)
at weblogic.work.PartitionUtility.runWorkUnderContext(PartitionUtility.java:41)
at weblogic.work.SelfTuningWorkManagerImpl.runWorkUnderContext(SelfTuningWorkManagerImpl.java:640)
at weblogic.work.ExecuteThread.execute(ExecuteThread.java:406)
at weblogic.work.ExecuteThread.run(ExecuteThread.java:346)
please help me. tnx
For me this occurs when the WSDL does not agree with the generated classes.

AsyncTask doInBackground to return multiple strings

I'm trying to build a very basic weather app in android studio. I am using AsyncClass to return multiple strings.
As you can see in the code, I used a class named "Wrapper" that is used to store my strings so I can just return a class object and use it in the onPostExecute method of the AsyncTask. The problem I am facing is that when I test the app, all of the returned Strings somehow are undefined (the default for the Wrapper class). This means the strings are not being updated in the doInBackground method and I can't seem to figure out why!
My Activity
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.i(MainActivity.class.getSimpleName(), "Can't connect to Google Play Services!");
}
private class Wrapper
{
String Temperature = "UNDEFINED";
String city = "UNDEFINED";
String country = "UNDEFINED";
}
private class GetWeatherTask extends AsyncTask<String, Void, Wrapper> {
private TextView textView;
public GetWeatherTask(TextView textView) {
this.textView = textView;
}
#Override
protected Wrapper doInBackground(String... strings) {
Wrapper w = new Wrapper();
String Temperature = "x";
String city = "y";
String country = "z";
try {
URL url = new URL(strings[0]);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
InputStream stream = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(stream));
StringBuilder builder = new StringBuilder();
String inputString;
while ((inputString = bufferedReader.readLine()) != null) {
builder.append(inputString);
}
JSONObject topLevel = new JSONObject(builder.toString());
JSONObject main = topLevel.getJSONObject("main");
JSONObject cityobj = topLevel.getJSONObject("city");
Temperature = String.valueOf(main.getDouble("temp"));
city = cityobj.getString("name");
country = cityobj.getString("country");
w.Temperature= Temperature;
w.city= city;
w.country=country;
urlConnection.disconnect();
} catch (IOException | JSONException e) {
e.printStackTrace();
}
return w;
}
#Override
protected void onPostExecute(Wrapper w) {
textView.setText("Current Temperature: " + w.Temperature + " C" + (char) 0x00B0
+"\n" + "Current Location: "+ w.country +"\n" + "City: "+ w.city );
}
}
}
UPDATE:
turned out that that I was using the wrong url in my code,I was using :
http://api.openweathermap.org/data/2.5/weather?lat=%f&lon=%f&units=%s&appid=%s
Instead I should've been using:
http://api.openweathermap.org/data/2.5/forecast?lat=%f&lon=%f&units=%s&appid=%s
-aka instead of weather I should've been using forcast
Your error starts here
JSONObject main = topLevel.getJSONObject("main");
Probably because the topLevel object has no "main" key.
{
"city":{ },
"cod":"200",
"message":0.1859,
"cnt":40,
"list":[ ]
}
Throw your JSON into here. https://jsonformatter.curiousconcept.com/
You'll notice that there are many, many "main" keys that are within the "list" element, but you have to parse those starting from getJSONArray("list").
Basically, something like this
String city = "undefined";
String country = "undefined";
List<Double> temperatures = new ArrayList<Double>();
try {
JSONObject object = new JSONObject(builder.toString());
JSONObject jCity = object.getJSONObject("city");
city = jCity.getString("name");
country = jCity.getString("country");
JSONArray weatherList = object.getJSONArray("list");
for (int i = 0; i < weatherList.length(); i++) {
JSONObject listObject = weatherList.getJSONObject(i);
double temp = listObject.getJSONObject("main").getDouble("temp");
temperatures.add(temp);
}
} catch (JSONException e) {
e.printStackTrace();
}
return new Wrapper(city, country, temperatures);
After studying your code, either your try block is failing, which is returning your object, but empty, or there is something wrong with your JSON parsing. If you could show us the JSON you are trying to parse that would be a great help.
That being said, the fact that it is still showing as "UNDEFINED" is because that is how you initialised it, and becuase (the JSON parse is likely failing), the object is being returned in an un-edited state.
EDIT:
You are parsing the JSON wrong. You are trying to find an object called "main" in the top directory, however the main object only exists inside of an array called list!
Please look here for a more easy to see and visual representation: http://prntscr.com/dlhlrk
You can use this site to help visualise your JSON and create an appropriate soluton based upon it. https://jsonformatter.curiousconcept.com/
Looking at the API you posted earlier (api.openweathermap.org) you are trying to access variables that don't exist. I suggest you have a look at what the API returns and try getting the variables one by one if you are getting a JSONException
EDIT:
What API you are using? In your initial post you said it was http://api.openweathermap.org/data/2.5/weather but in a comment above you said it was http://api.openweathermap.org/data/2.5/forecast.
If you're using the weather API (as initially stated) you can use the below:
#Override
protected Wrapper doInBackground(String... strings) {
Wrapper w = new Wrapper();
try {
URL url = new URL(strings[0]);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
InputStream stream = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(stream));
StringBuilder builder = new StringBuilder();
String inputString;
while ((inputString = bufferedReader.readLine()) != null) {
builder.append(inputString);
}
Log.d("JSON", builder.toString());
JSONObject topLevel = new JSONObject(builder.toString());
JSONObject main = topLevel.getJSONObject("main");
JSONObject sys = topLevel.getJSONObject("sys");
w.Temperature = String.valueOf(main.getDouble("temp"));
w.city = topLevel.getString("name");
w.country = sys.getString("country");
urlConnection.disconnect();
} catch (IOException | JSONException e) {
e.printStackTrace();
}
return w;
}

Error when sending a POST request, authenticated by OAuth, using signpost

I'm trying to send aמ HTTP POST request in order to send contacts information to a Mail Exchange Server, using their API (creating a new "subscriber"). I'm using Java and java.util.HttpURLConnection.
When I try signing the connection, I'm getting a null reference exception. If I try signing the connection prior to adding the setRequestProperty headers, I'm getting an Invalid Signature response from the server.
Using a GET request with the same general procedure works - which means, as far as I understand, that my signing method (and key values etc.) is OK.
The service I'm trying to use has some kind of a "SDK" available, written in .NET. I didn't try to use it but I do believe it to work (they declare so).
I tried to replicate their procedure. Below you can find my code, follow by theirs:
private static HttpURLConnection createAndSendOAuthPostRequestWithParams () throws MalformedURLException, IOException, Exception {
String url = "http://apisdomain/v1.0/lists/354467/subscribers";
// Here I set up the values given by the provider (API's admin) which I removed from the example
String clientKey = "";
String clientSecret = "";
String userKey = "";
String userSecret = "";
String postData = "NAME=TestSubscriber&EMAIL=test#gmail.com
byte[] postBody = postData.getBytes("UTF-8");
URL apiUrl = new URL(url);
HttpURLConnection connection = (HttpURLConnection) apiUrl.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("content-length", String.valueOf(postBody.length));
connection.setRequestProperty("content-type", "application/x-www-form-urlencoded; charset=UTF-8");
//OAuth
OAuthConsumer consumer = new DefaultOAuthConsumer (clientKey, clientSecret);
//consumer.setAdditionalParameters(parameters);
consumer.setTokenWithSecret(userKey, userSecret);
HttpRequest httpReq = consumer.sign(connection); //Where the exception occurs
if (!postBody.toString().isEmpty()) {
connection.setDoOutput(true);
try (DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream())) {
outputStream.write(postBody);
outputStream.flush();
}
}
return connection;
}
From thier SDK:
using System.Text;
namespace ResponderSDK
{
using OAuth;
using System;
using System.Collections.Generic;
using System.Net;
using System.IO;
class ResponderOAuth
{
/* Contains the last HTTP status code returned. */
public HttpStatusCode http_code;
/* Contains the last API call. */
public string url;
/* Set up the API root URL. */
public string host = "http://api.responder.co.il/v1.0/";
/* Set timeout default. */
public int timeout = 3000;
/* Set connect timeout. */
public int connect_timeout = 30;
/* Verify SSL Cert. */
public bool ssl_verifypeer = false;
/* Response format. */
public string format = "json";
/* Contains the last HTTP headers returned. */
public string http_info;
/* Set the useragent. */
public string useragent = "ResponderOAuth v0.1-beta";
/*debug info*/
public string headers_string;
public string base_string;
public string post_string;
/* Signature */
private OAuthSignatureMethod_HMAC_SHA1 signature;
/* OAuthConsumer */
private OAuthConsumer consumer;
/* Token */
private OAuthToken token;
public ResponderOAuth(string consumer_key, string consumer_secret, string oauth_token = null, string oauth_token_secret = null)
{
this.signature = new OAuthSignatureMethod_HMAC_SHA1();
this.consumer = new OAuthConsumer(consumer_key, consumer_secret);
if (!String.IsNullOrEmpty(oauth_token) && !String.IsNullOrEmpty(oauth_token_secret))
{
this.token = new OAuthToken(oauth_token, oauth_token_secret);
}
else
{
this.token = null;
}
}
public string http_request(string url, string method = "GET", ParametersArray parameters = null)
{
method = method.ToUpper();
if (url.LastIndexOf("https://") != 0 && url.LastIndexOf("http://") != 0)
{
url = String.Format("{0}{1}", this.host, url);
}
if (method.Equals("GET"))
parameters = null;
OAuthRequest request = OAuthRequest.from_consumer_and_token(this.consumer, this.token, method, url, parameters);
request.sign_request(this.signature, this.consumer, this.token);
this.base_string = request.base_string;
if (method.Equals("GET"))
return this.http(request.to_url(), "GET", request.to_header(), null);
else
return this.http(request.get_normalized_http_url(), method, request.to_header(), request.to_postdata());
}
private string http(string url, string method, WebHeaderCollection headers, string data = null)
{
List<string> new_http_info = new List<string>();
ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications);
HttpWebRequest request = null;
if (!method.Equals("DELETE"))
request = (HttpWebRequest)WebRequest.Create(url);
else
{
if (!String.IsNullOrEmpty(data))
{
url = String.Format("{0}?{1}", url, data);
}
request = (HttpWebRequest)WebRequest.Create(url);
}
/* WebRequest settings */
((HttpWebRequest)request).ProtocolVersion = System.Net.HttpVersion.Version10;
((HttpWebRequest)request).UserAgent = this.useragent;
((HttpWebRequest)request).ContinueTimeout = this.connect_timeout;
((HttpWebRequest)request).Timeout = this.timeout;
((HttpWebRequest)request).Headers = headers;
((HttpWebRequest)request).UseDefaultCredentials = true;
((HttpWebRequest)request).PreAuthenticate = true;
((HttpWebRequest)request).Credentials = CredentialCache.DefaultCredentials;
this.headers_string = headers.ToString();
this.post_string = data;
byte[] dataByteArray = null;
if ((!String.IsNullOrEmpty(data) && method.Equals("POST")) || method.Equals("PUT"))
{
((HttpWebRequest)request).ContentType = "application/x-www-form-urlencoded";
System.Text.Encoding encoding = System.Text.Encoding.UTF8;
dataByteArray = encoding.GetBytes(data);
((HttpWebRequest)request).ContentLength = dataByteArray.Length;
((HttpWebRequest)request).Expect = "";
}
switch (method)
{
case "POST":
((HttpWebRequest)request).Method = "POST";
if (!String.IsNullOrEmpty(data))
{
Stream dataPost = request.GetRequestStream();
dataPost.Write(dataByteArray, 0, dataByteArray.Length);
dataPost.Close();
}
break;
case "PUT":
((HttpWebRequest)request).Method = "PUT";
if (!String.IsNullOrEmpty(data))
{
Stream dataPost = request.GetRequestStream();
dataPost.Write(dataByteArray, 0, dataByteArray.Length);
dataPost.Close();
}
break;
case "DELETE":
((HttpWebRequest)request).Method = "DELETE";
break;
}
WebResponse response = request.GetResponse();
this.http_code = ((HttpWebResponse)response).StatusCode;
// Get the stream containing content returned by the server.
Stream dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
return reader.ReadToEnd();
}
}
}
If your input String format is json, you can change content-type to "application/json" and try signing in after adding the setRequestProperty headers.

Verify OAuth1a signed request using Twitter joauth with RSA-SHA1?

I have a use case to authenticate OAuth1 request which is signed using RSA Private Key and verified at server end with RSA public key.
I found this library from Twitter which helps us authenticate/verify the Oauth signed requests. https://github.com/twitter/joauth
I want to leverage this library for verifying the request from Jersey or Spring MVC action method. The request from client would have been signed using private key. At my end I would use the public key of the client to verify the request. which means RSA-SHA1 algo.
Twitter joauth seem to be useful but I am missing the code that would transform HttpServletRequest to OAuthRequest
The library read-me file suggests this as facility but I could not find a code that does javax.servlet.http.HttpServletRequest --> com.twitter.joauth.OAuthRequest transformation.
The request verification happens in verify method which has following signature.
public VerifierResult verify(UnpackedRequest.OAuth1Request request, String tokenSecret, String consumerSecret);
Secondly I also want to know which is the most appropriate way to use/read RSA public key with twitter joauth when verify method takes String parameter ?
I have never used any library to authenticate users via Twitter. But I have just looked in the UnpackedRequest.OAuth1Request. You can create an instance of this class by filling all parameters. I have written Twitter OAuth Header creator, so you can just use it to fill those parameters or send POST requests directly without a library.
Here all classes what you need:
Signature - to generate an OAuth Signature.
public class Signature {
private static final String HMAC_SHA1_ALGORITHM = "HmacSHA1";
public static String calculateRFC2104HMAC(String data, String key)
throws java.security.SignatureException
{
String result;
try {
SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(), HMAC_SHA1_ALGORITHM);
Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM);
mac.init(signingKey);
byte[] rawHmac = mac.doFinal(data.getBytes());
result = new String(Base64.encodeBase64(rawHmac));
} catch (Exception e) {
throw new SignatureException("Failed to generate HMAC : " + e.getMessage());
}
return result;
}
}
NvpComparator - to sort parameters you need in the header.
public class NvpComparator implements Comparator<NameValuePair> {
#Override
public int compare(NameValuePair arg0, NameValuePair arg1) {
String name0 = arg0.getName();
String name1 = arg1.getName();
return name0.compareTo(name1);
}
}
OAuth - for URL encode.
class OAuth{
...
public static String percentEncode(String s) {
return URLEncoder.encode(s, "UTF-8")
.replace("+", "%20").replace("*", "%2A")
.replace("%7E", "~");
}
...
}
HeaderCreator - to create all needed parameters and generate an OAuth header param.
public class HeaderCreator {
private String authorization = "OAuth ";
private String oAuthSignature;
private String oAuthNonce;
private String oAuthTimestamp;
private String oAuthConsumerSecret;
private String oAuthTokenSecret;
public String getAuthorization() {
return authorization;
}
public String getoAuthSignature() {
return oAuthSignature;
}
public String getoAuthNonce() {
return oAuthNonce;
}
public String getoAuthTimestamp() {
return oAuthTimestamp;
}
public HeaderCreator(){}
public HeaderCreator(String oAuthConsumerSecret){
this.oAuthConsumerSecret = oAuthConsumerSecret;
}
public HeaderCreator(String oAuthConsumerSecret, String oAuthTokenSecret){
this(oAuthConsumerSecret);
this.oAuthTokenSecret = oAuthTokenSecret;
}
public String getTwitterServerTime() throws IOException, ParseException {
HttpsURLConnection con = (HttpsURLConnection)
new URL("https://api.twitter.com/oauth/request_token").openConnection();
con.setRequestMethod("HEAD");
con.getResponseCode();
String twitterDate= con.getHeaderField("Date");
DateFormat formatter = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z", Locale.ENGLISH);
Date date = formatter.parse(twitterDate);
return String.valueOf(date.getTime() / 1000L);
}
public String generatedSignature(String url, String method, List<NameValuePair> allParams,
boolean withToken) throws SignatureException {
oAuthNonce = String.valueOf(System.currentTimeMillis());
allParams.add(new BasicNameValuePair("oauth_nonce", oAuthNonce));
try {
oAuthTimestamp = getTwitterServerTime();
allParams.add(new BasicNameValuePair("oauth_timestamp", oAuthTimestamp));
}catch (Exception ex){
//TODO: Log!!
}
Collections.sort(allParams, new NvpComparator());
StringBuffer params = new StringBuffer();
for(int i=0;i<allParams.size();i++)
{
NameValuePair nvp = allParams.get(i);
if (i>0) {
params.append("&");
}
params.append(nvp.getName() + "=" + OAuth.percentEncode(nvp.getValue()));
}
String signatureBaseStringTemplate = "%s&%s&%s";
String signatureBaseString = String.format(signatureBaseStringTemplate,
OAuth.percentEncode(method),
OAuth.percentEncode(url),
OAuth.percentEncode(params.toString()));
String compositeKey = OAuth.percentEncode(oAuthConsumerSecret)+"&";
if(withToken) compositeKey+=OAuth.percentEncode(oAuthTokenSecret);
oAuthSignature = Signature.calculateRFC2104HMAC(signatureBaseString, compositeKey);
return oAuthSignature;
}
public String generatedAuthorization(List<NameValuePair> allParams){
authorization = "OAuth ";
Collections.sort(allParams, new NvpComparator());
for(NameValuePair nvm : allParams){
authorization+=nvm.getName()+"="+OAuth.percentEncode(nvm.getValue())+", ";
}
authorization=authorization.substring(0,authorization.length()-2);
return authorization;
}
}
Explain:
1. getTwitterServerTime
In oAuthTimestamp you need not your time of server but the time of a Twitter server. You can optimize it saving this param if you always send requests in the certain Twitter server.
2. HeaderCreator.generatedSignature(...)
url - logically url to twitter API
method - GET or POST. You must use always "POST"
allParams - Parameters which you know to generate signature ("param_name", "param_value");
withToken - if you know oAuthTokenSecret put true. Otherwise false.
3. HeaderCreator.generatedAuthorization(...)
Use this method after generatedSignature(...) to generate an OAuth header string.
allParams - it is parameters which you have used in generatedSignature(...) plus: nonce, signature, timestamp. Always use:
allParams.add(new BasicNameValuePair("oauth_nonce", headerCreator.getoAuthNonce()));
allParams.add(new BasicNameValuePair("oauth_signature", headerCreator.getoAuthSignature()));
allParams.add(new BasicNameValuePair("oauth_timestamp", headerCreator.getoAuthTimestamp()));
Now you can use it to fill UnpackedRequest.OAuth1Request in your library. Also here an example to authenticate user in SpringMVC without the library:
Requests - to send post requests.
public class Requests {
public static String sendPost(String url, String urlParameters, Map<String, String> prop) throws Exception {
URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
con.setRequestMethod("POST");
if(prop!=null) {
for (Map.Entry<String, String> entry : prop.entrySet()) {
con.setRequestProperty(entry.getKey(), entry.getValue());
}
}
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
BufferedReader in;
if(responseCode==200) {
in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
}else{
in = new BufferedReader(
new InputStreamReader(con.getErrorStream()));
}
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
return response.toString();
}
}
twAuth(...) - put it in your controller. Execute it when an user want to authenticate in your site via Twitter.
#RequestMapping(value = "/twauth", method = RequestMethod.GET)
#ResponseBody
public String twAuth(HttpServletResponse response) throws Exception{
try {
String url = "https://api.twitter.com/oauth/request_token";
List<NameValuePair> allParams = new ArrayList<NameValuePair>();
allParams.add(new BasicNameValuePair("oauth_callback", "http://127.0.0.1:8080/twlogin"));
allParams.add(new BasicNameValuePair("oauth_consumer_key", "2YhNLyum1VY10UrWBMqBnatiT"));
allParams.add(new BasicNameValuePair("oauth_signature_method", "HMAC-SHA1"));
allParams.add(new BasicNameValuePair("oauth_version", "1.0"));
HeaderCreator headerCreator = new HeaderCreator("RUesRE56vVWzN9VFcfA0jCBz9VkvkAmidXj8d1h2tS5EZDipSL");
headerCreator.generatedSignature(url,"POST",allParams,false);
allParams.add(new BasicNameValuePair("oauth_nonce", headerCreator.getoAuthNonce()));
allParams.add(new BasicNameValuePair("oauth_signature", headerCreator.getoAuthSignature()));
allParams.add(new BasicNameValuePair("oauth_timestamp", headerCreator.getoAuthTimestamp()));
Map<String, String> props = new HashMap<String, String>();
props.put("Authorization", headerCreator.generatedAuthorization(allParams));
String twitterResponse = Requests.sendPost(url,"",props);
Integer indOAuthToken = twitterResponse.indexOf("oauth_token");
String oAuthToken = twitterResponse.substring(indOAuthToken, twitterResponse.indexOf("&",indOAuthToken));
response.sendRedirect("https://api.twitter.com/oauth/authenticate?" + oAuthToken);
}catch (Exception ex){
//TODO: Log
throw new Exception();
}
return "main";
}
twLogin(...) - put it in your controller. It is callback from Twitter.
#RequestMapping(value = "/twlogin", method = RequestMethod.GET)
public String twLogin(#RequestParam("oauth_token") String oauthToken,
#RequestParam("oauth_verifier") String oauthVerifier,
Model model, HttpServletRequest request){
try {
if(oauthToken==null || oauthToken.equals("") ||
oauthVerifier==null || oauthVerifier.equals(""))
return "main";
String url = "https://api.twitter.com/oauth/access_token";
List<NameValuePair> allParams = new ArrayList<NameValuePair>();
allParams.add(new BasicNameValuePair("oauth_consumer_key", "2YhNLyum1VY10UrWBMqBnatiT"));
allParams.add(new BasicNameValuePair("oauth_signature_method", "HMAC-SHA1"));
allParams.add(new BasicNameValuePair("oauth_token", oauthToken));
allParams.add(new BasicNameValuePair("oauth_version", "1.0"));
NameValuePair oAuthVerifier = new BasicNameValuePair("oauth_verifier", oauthVerifier);
allParams.add(oAuthVerifier);
HeaderCreator headerCreator = new HeaderCreator("RUesRE56vVWzN9VFcfA0jCBz9VkvkAmidXj8d1h2tS5EZDipSL");
headerCreator.generatedSignature(url,"POST",allParams,false);
allParams.add(new BasicNameValuePair("oauth_nonce", headerCreator.getoAuthNonce()));
allParams.add(new BasicNameValuePair("oauth_signature", headerCreator.getoAuthSignature()));
allParams.add(new BasicNameValuePair("oauth_timestamp", headerCreator.getoAuthTimestamp()));
allParams.remove(oAuthVerifier);
Map<String, String> props = new HashMap<String, String>();
props.put("Authorization", headerCreator.generatedAuthorization(allParams));
String twitterResponse = Requests.sendPost(url,"oauth_verifier="+oauthVerifier,props);
//Get user id
Integer startIndexTmp = twitterResponse.indexOf("user_id")+8;
Integer endIndexTmp = twitterResponse.indexOf("&",startIndexTmp);
if(endIndexTmp<=0) endIndexTmp = twitterResponse.length()-1;
Long userId = Long.parseLong(twitterResponse.substring(startIndexTmp, endIndexTmp));
//Do what do you want...
}catch (Exception ex){
//TODO: Log
throw new Exception();
}
}

How to encapsulate the logic of parametrized messages?

I'm using java.util.resourcebundle to format my JSTL messages and this works fine:
I use the class MessageFormat you can see here. Now I want to encapsulate this to a method that is just getParametrizedMessage(String key, String[]parameters) but I'm not sure how to do it. Now there is quite a lot of work to display just one or two messages with parameters:
UserMessage um = null;
ResourceBundle messages = ResourceBundle.getBundle("messages");
String str = messages.getString("PF1");
Object[] messageArguments = new String[]{nyreg.getNummer()};
MessageFormat formatter = new MessageFormat("");
formatter.applyPattern(messages.getString("PI14"));
String outputPI14 = formatter.format(messageArguments);
formatter.applyPattern(messages.getString("PI15"));
String outputPI15 = formatter.format(messageArguments)
if(ipeaSisFlag)
if(checkIfPCTExistInDB && nyreg.isExistInDB()) {
//um = new ExtendedUserMessage(MessageHandler.getParameterizedMessage("PI15", new String[]{nyreg.getNummer()}) , UserMessage.TYPE_INFORMATION, "Info");
um = new ExtendedUserMessage(outputPI15 , UserMessage.TYPE_INFORMATION, "Info");
…and so on. Now can I move this logic to a static class MessageHandler.getParameterizedMessage that now is not working and looking like this:
private final static String dictionaryFileName="messages.properties";
public static String getParameterizedMessage(String key, String [] params){
if (dictionary==null){
loadDictionary();
}
return getParameterizedMessage(dictionary,key,params);
}
private static void loadDictionary(){
String fileName = dictionaryFileName;
try {
dictionary=new Properties();
InputStream fileInput = MessageHandler.class.getClassLoader().getResourceAsStream(fileName);
dictionary.load(fileInput);
fileInput.close();
}
catch(Exception e) {
System.err.println("Exception reading propertiesfile in init "+e);
e.printStackTrace();
dictionary=null;
}
}
How can I make using my parametrized messages as easy as calling a method with key and parameter?
Thanks for any help
Update
The logic comes from an inherited method that in in the abstract class that this extends. The method looks like:
protected static String getParameterizedMessage(Properties dictionary,String key,String []params){
if (dictionary==null){
return "ERROR";
}
String msg = dictionary.getProperty(key);
if (msg==null){
return "?!Meddelande " +key + " saknas!?";
}
if (params==null){
return msg;
}
StringBuffer buff = new StringBuffer(msg);
for (int i=0;i<params.length;i++){
String placeHolder = "<<"+(i+1)+">>";
if (buff.indexOf(placeHolder)!=-1){
replace(buff,placeHolder,params[i]);
}
else {
remove(buff,placeHolder);
}
}
return buff.toString();
}
I think I must rewrite the above method in order to make it work like a resourcebundle rather than just a dictionary.
Update 2
The code that seems to work is here
public static String getParameterizedMessage(String key, Object [] params){
ResourceBundle messages = ResourceBundle.getBundle("messages");
MessageFormat formatter = new MessageFormat("");
formatter.applyPattern(messages.getString(key));
return formatter.format(params);
}
I'm not really sure what you're trying to achive, here's what I did in the past:
public static final String localize(final Locale locale, final String key, final Object... param) {
final String name = "message";
final ResourceBundle rb;
/* Resource bundles are cached internally,
never saw a need to implement another caching level
*/
try {
rb = ResourceBundle.getBundle(name, locale, Thread.currentThread()
.getContextClassLoader());
} catch (MissingResourceException e) {
throw new RuntimeException("Bundle not found:" + name);
}
String keyValue = null;
try {
keyValue = rb.getString(key);
} catch (MissingResourceException e) {
// LOG.severe("Key not found: " + key);
keyValue = "???" + key + "???";
}
/* Message formating is expensive, try to avoid it */
if (param != null && param.length > 0) {
return MessageFormat.format(keyValue, param);
} else {
return keyValue;
}
}

Categories