We're running RESTEasy 2.3.0.GA here and I'm struggling with a https://stackoverflow.com/questions/18219237/jax-rs-path-regex-fails-for-just-one-of-an-or-expression and I can't figure out how to get RESTEasy to fess'up why it thinks a particular URI is not mapped to my handler. Is there some debug level I can crank up to get RESTEasy to reveal its dispatch?
The docs are vague about what you'll get, but the Logger they are using log4j, logback, and java.util.logging. In my case, adding the following to logback.xml gives me some sparse information.
<logger name="org.jboss.resteasy.core" level="debug" />
<logger name="org.jboss.resteasy.specimpl" level="debug" />
<logger name="org.jboss.resteasy.plugins.server" level="debug" />
http://docs.jboss.org/resteasy/docs/2.3.0.GA/userguide/html/Installation_Configuration.html#RESTEasyLogging
This worked for me:
#Provider
#ServerInterceptor
public class LoggingInterceptor implements ContainerRequestFilter {
private static final ObjectMapper MAPPER = new ObjectMapper();
#Override
public void filter(ContainerRequestContext containerRequestContext) throws IOException {
if (REQUESTS_LOGGER.isDebugEnabled()) {
final String method = containerRequestContext.getMethod();
final String url = containerRequestContext.getUriInfo().getRequestUri().toString();
final StringBuilder headersStr = new StringBuilder();
MultivaluedMap<String, String> headers = containerRequestContext.getHeaders();
for (MultivaluedMap.Entry<String, List<String>> header : headers.entrySet()) {
headersStr.append(header.getKey()).append(": ").append(header.getValue()).append('\n');
}
String json = null;
if ("POST".equals(method) || "PUT".equals(method)) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
IOUtils.copy(containerRequestContext.getEntityStream(), baos);
byte[] jsonBytes = baos.toByteArray();
json = new String(jsonBytes, "UTF-8");
Object jsonObject = MAPPER.readValue(json, Object.class);
json = MAPPER.writeValueAsString(jsonObject);
containerRequestContext.setEntityStream(new ByteArrayInputStream(jsonBytes));
}
REQUESTS_LOGGER.restCall(method, url, headersStr.toString(), json == null ? "empty" : json);
}
}
}
Related
I'm not a developer and we don't have one currently on our staff. So I looked all over the web and modified this Apex Class to suit my needs so that when an opportunity is marked as closed/won I get a small message in Slack.
It works great and I'd like to send this to Production. However, I didn't realize that I need to include a test for this and I am stuck on what that means.
Here's my Apex Class:
public with sharing class SlackPublisher {
private static final String SLACK_URL = 'https://hooks.slack.com/services/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';
public class Oppty {
#InvocableVariable(label='Opportunity Name')
public String opptyName;
#InvocableVariable(label='Opportunity Owner')
public String opptyOwnerName;
#InvocableVariable(label='Account Name')
public String acctName;
#InvocableVariable(label='Amount')
public String amount;
}
public class UrlMethods {
String BaseUrl; // The Url w/o the page (ex: 'https://na9.salesforce.com/')
String PageUrl; // The Url of the page (ex: '/apex/SomePageName')
String FullUrl; // The full Url of the current page w/query string parameters
// (ex: 'https://na9.salesforce.com/apex/SomePageName?x=1&y=2&z=3')
String Environment; // Writing code that can detect if it is executing in production or a sandbox
// can be extremely useful especially if working with sensitive data.
public UrlMethods() { // Constructor
BaseUrl = URL.getSalesforceBaseUrl().toExternalForm(); // (Example: 'https://na9.salesforce.com/')
}
}
#InvocableMethod(label='Post to Slack')
public static void postToSlack ( List<Oppty> opps ) {
Oppty o = opps[0]; // bulkify the code later
Map<String,Object> msg = new Map<String,Object>();
msg.put('text','Deal ' + o.opptyName + ' was just Closed/Won' + ':champagne:' + '\n' + 'for a total of ' + '$' + o.amount);
msg.put('mrkdwn', true);
String body = JSON.serialize(msg);
System.enqueueJob(new QueueableSlackPost(SLACK_URL, 'POST', body));
}
public class QueueableSlackPost implements System.Queueable, Database.AllowsCallouts {
private final String url;
private final String method;
private final String body;
public QueueableSlackPost(String url, String method, String body) {
this.url = url;
this.method = method;
this.body = body;
}
public void execute(System.QueueableContext ctx) {
HttpRequest req = new HttpRequest();
req.setEndpoint(url);
req.setMethod(method);
req.setBody(body);
Http http = new Http();
HttpResponse res = http.send(req);
}
}
}
and what I found online as a base for a test was this:
#isTest
private class SlackOpportunityPublisherTest {
private class RestMock implements HttpCalloutMock {
public HTTPResponse respond(HTTPRequest req) {
String fullJson = 'your Json Response';
HTTPResponse res = new HTTPResponse();
res.setHeader('Content-Type', 'text/json');
res.setBody(fullJson);
res.setStatusCode(200);
return res;
}
}
static testMethod void service_call() {
Test.setMock(HttpCalloutMock.class, new RestMock());
Test.startTest();
//your webserive call code
Database.GetUpdatedResult r =
Database.getUpdated(
'amount',
Datetime.now().addHours(-1),
Datetime.now());
Test.StopTest();
}
}
When I try to validate this in production it says it only gives me 68% coverage and I need 75%. Can someone help me write the test so that I can put into Prod?
I'm trying to throw an exception if HTTP response code is anything other than 200 or 201. I tried to override http4.DefaultHttpBinding, but the class is never getting called. What am I doing wrong here?
public class CustomHttpBinding extends org.apache.camel.component.http4.DefaultHttpBinding {
Logger log = Logger.getLogger(CustomHttpBinding.class);
private static final Integer HTTP_OK = 200;
private static final Integer HTTP_CREATED = 201;
#Override
public void doWriteResponse(Message message, HttpServletResponse response, Exchange exchange) throws IOException {
Integer httpResponseCode = message.getHeader(Exchange.HTTP_RESPONSE_CODE, Integer.class);
if(!httpResponseCode.equals(HTTP_OK) && !httpResponseCode.equals(HTTP_CREATED) ) {
throw new IOException("HTTP error code for HLR response is " + httpResponseCode);
}
else {
super.doWriteResponse(message, response, exchange);
}
}
}
In xml:
<bean id="customHttpBinding" class="com.test.response.CustomHttpBinding" />
<endpoint uri="http4:${http.url.1}?httpBinding=#customHttpBinding&httpClient.socketTimeout=${http.notificationTimeout}" id="http4.1.to"/>
If the http response code is 300+, the binding will throw exception before it calls doWriteResponse(...). Try overriding writeResponse(...) in your custom binding, and verify that your binding is used.
I am trying to form a query in solr for data import but could not able to do so.
I need to form the below query:
http://salsa23q-XXX-08.XXX.XXX.com:8080/solr/#/geoloc_replica1/dataimport/?command=full-import&clean=true
The code I am trying:
public class SolrJDB
{
public static String url = "http://salsa23q-XXX-08.XXX.XXX.com:8080/solr:8080/solr";
public static SolrServer localserver;
public static CloudSolrServer cloudserver;// = new CloudSolrServer("url");
public static SolrQuery que;
public static SolrInputDocument doc;
public static SolrDocumentList list;
public static QueryResponse response;
public static String serverurl = "http://salsa23q-XXX-08.XXX.XXX.com:8080/solr";
public static void main(String[] args) throws MalformedURLException, SQLException, SolrServerException {
try{
System.out.println("+++++++++++++ Starting here +++++++++++++++++++++");
//Cloud Server
String url = "salsa23q-XXX-08.XXX.XXX.com:8080/solr";
cloudserver = new CloudSolrServer(url);
SolrQuery parameters = new SolrQuery();
parameters.set("qt","/geoloc_replica1");
parameters.set("qt","//dataimport");
parameters.set("command","full-import");
System.out.println("Query to be Executed ============"+parameters.toString());
QueryResponse response = cloudserver.query(parameters);
SolrDocumentList list = response.getResults();
}
catch(SolrServerException e){
System.out.println(e.toString());
e.printStackTrace();
}
catch(Exception e){
System.out.println(e.toString());
e.printStackTrace();
}
}
}
I am getting following error:
org.apache.solr.client.solrj.SolrServerException: Error executing query
at org.apache.solr.client.solrj.request.QueryRequest.process(QueryRequest.java:98)
at org.apache.solr.client.solrj.SolrServer.query(SolrServer.java:301)
at SolrJDB.main(SolrJDB.java:37)
Caused by: java.lang.RuntimeException
at org.apache.solr.common.cloud.SolrZkClient.<init>(SolrZkClient.java:115)
at org.apache.solr.common.cloud.SolrZkClient.<init>(SolrZkClient.java:83)
at org.apache.solr.common.cloud.ZkStateReader.<init>(ZkStateReader.java:138)
at org.apache.solr.client.solrj.impl.CloudSolrServer.connect(CloudSolrServer.java:140)
at org.apache.solr.client.solrj.impl.CloudSolrServer.request(CloudSolrServer.java:165)
at org.apache.solr.client.solrj.request.QueryRequest.process(QueryRequest.java:90)
... 2 more
You are mixing up things in your code. You want to perform a request to run a DataImportHandler. But you are constructing a SolrQuery. The latter represents a search request.
What you need to run a DataImportHandler via the Java API is an UpdateRequest.
public int runDataImportHandler() throws Exception {
// fill in the parameters you want to run your import with
ModifiableSolrParams tmpParams = new ModifiableSolrParams();
tmpParams.set("command", "full-import");
tmpParams.set("clean", true);
tmpParams.set("commit", true);
tmpParams.set("optimize", true);
// create the update request
UpdateRequest tmpRequest = new UpdateRequest("/dataimport");
tmpRequest.setParams(tmpParams);
SolrServer tmpServer = getServer();
tmpRequest.process(tmpServer);
ModifiableSolrParams tmpStatusParams = new ModifiableSolrParams();
tmpStatusParams.set("command", "status");
String tmpStatus = "busy";
int tmpProcessed = 0;
do {
System.out.println("waiting for import to finish, status was " + tmpStatus);
Thread.sleep(500);
UpdateRequest tmpStatusRequest = new UpdateRequest("/dataimport");
tmpStatusRequest.setParams(tmpStatusParams);
UpdateResponse tmpStatusResponse = tmpStatusRequest.process(tmpServer);
tmpStatus = tmpStatusResponse.getResponse().get("status").toString();
Map tmpMessages = (Map) tmpStatusResponse.getResponse().get("statusMessages");
System.out.println("import status is " + tmpStatus);
if (tmpMessages.get("Total Documents Processed") != null) {
tmpProcessed = Integer.valueOf(tmpMessages.get("Total Documents Processed").toString());
}
} while ("busy".equals(tmpStatus));
System.out.println("import done");
return tmpProcessed;
}
As I can see your code the exception is related to how CloudSolrServer instance is created :-
To make instance of CloudSolrServer you need to have Solr in Cloud mode and the URL used here will be zookeeper address. CloudSolrServer creates zkStateReader which gets live nodes and collection from which it query.
Following is the exact way how you would be creating the code for dataimport:-
public static void main(String[] args) throws SolrServerException, IOException {
ModifiableSolrParams params = new ModifiableSolrParams();
params.set(UpdateParams.COLLECTION, "collection1");
params.set(CommonParams.QT, "/dataimport");
params.set("command", "full-import");
params.set("claen", true);
params.set(UpdateParams.COMMIT, true);
params.set(UpdateParams.OPTIMIZE, true);
String url = "localhost:9983"; /*Zookeeper Address*/
CloudSolrServer cloudserver = new CloudSolrServer(url, true);
cloudserver.setDefaultCollection("test");/*This is necessary in case if you are not specifying any collection name in dataimport*/
cloudserver.query(params);
}
I am looking to implement a route where reslet/cxfrs end point will accept file as multipart request and process. (Request may have some JSON data as well.
Thanks in advance.
Regards.
[EDIT]
Have tried following code. Also tried sending file using curl. I can see file related info in headers and debug output, but not able to retrieve attachment.
from("servlet:///hello").process(new Processor() {
#Override
public void process(Exchange exchange) throws Exception {
Message in = exchange.getIn();
StringBuffer v = new StringBuffer();
HttpServletRequest request = (HttpServletRequest) in
.getHeaders().get(Exchange.HTTP_SERVLET_REQUEST);
DiskFileItemFactory diskFile = new DiskFileItemFactory();
FileItemFactory factory = diskFile;
ServletFileUpload upload = new ServletFileUpload(factory);
List items = upload.parseRequest(request);
.....
curl :
curl -vvv -i -X POST -H "Content-Type: multipart/form-data" -F "image=#/Users/navaltiger/1.jpg; type=image/jpg" http://:8080/JettySample/camel/hello
following code works (but can't use as it embeds jetty, and we would like to deploy it on tomcat/weblogic)
public void configure() throws Exception {
// getContext().getProperties().put("CamelJettyTempDir", "target");
getContext().setStreamCaching(true);
getContext().setTracing(true);
from("jetty:///test").process(new Processor() {
// from("servlet:///hello").process(new Processor() {
public void process(Exchange exchange) throws Exception {
String body = exchange.getIn().getBody(String.class);
HttpServletRequest request = exchange.getIn().getBody(
HttpServletRequest.class);
StringBuffer v = new StringBuffer();
// byte[] picture = (request.getParameter("image")).getBytes();
v.append("\n Printing All Request Parameters From HttpSerlvetRequest: \n+"+body +" \n\n");
Enumeration<String> requestParameters = request
.getParameterNames();
while (requestParameters.hasMoreElements()) {
String paramName = (String) requestParameters.nextElement();
v.append("\n Request Paramter Name: " + paramName
+ ", Value - " + request.getParameter(paramName));
}
I had a similar problem and managed to resolve inspired by the answer of brentos. The rest endpoint in my case is defined via xml:
<restContext id="UploaderServices" xmlns="http://camel.apache.org/schema/spring">
<rest path="/uploader">
<post bindingMode="off" uri="/upload" produces="application/json">
<to uri="bean:UploaderService?method=uploadData"/>
</post>
</rest>
</restContext>
I had to use "bindingMode=off" to disable xml/json unmarshalling because the HttpRequest body contains multipart data (json/text+file) and obviously the standard unmarshaling process was unable to process the request because it's expecting a string in the body and not a multipart payload.
The file and other parameters are sent from a front end that uses the file upload angular module: https://github.com/danialfarid/ng-file-upload
To solve CORS problems I had to add a CORSFilter filter in the web.xml like the one here:
public class CORSFilter implements Filter {
#Override
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException,
ServletException {
HttpServletResponse httpResp = (HttpServletResponse) resp;
HttpServletRequest httpReq = (HttpServletRequest) req;
httpResp.setHeader("Access-Control-Allow-Methods", "GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS, CONNECT, PATCH");
httpResp.setHeader("Access-Control-Allow-Origin", "*");
if (httpReq.getMethod().equalsIgnoreCase("OPTIONS")) {
httpResp.setHeader("Access-Control-Allow-Headers",
httpReq.getHeader("Access-Control-Request-Headers"));
}
chain.doFilter(req, resp);
}
#Override
public void init(FilterConfig arg0) throws ServletException {
}
#Override
public void destroy() {
}
}
Also, I had to modify a little bit the unmarshaling part:
public String uploadData(Message exchange) {
String contentType=(String) exchange.getIn().getHeader(Exchange.CONTENT_TYPE);
MediaType mediaType = MediaType.valueOf(contentType); //otherwise the boundary parameter is lost
InputRepresentation representation = new InputRepresentation(exchange
.getBody(InputStream.class), mediaType);
try {
List<FileItem> items = new RestletFileUpload(
new DiskFileItemFactory())
.parseRepresentation(representation);
for (FileItem item : items) {
if (!item.isFormField()) {
InputStream inputStream = item.getInputStream();
// Path destination = Paths.get("MyFile.jpg");
// Files.copy(inputStream, destination,
// StandardCopyOption.REPLACE_EXISTING);
System.out.println("found file in request:" + item);
}else{
System.out.println("found string in request:" + new String(item.get(), "UTF-8"));
}
}
} catch (Exception e) {
e.printStackTrace();
}
return "200";
}
I'm using the Camel REST DSL with Restlet and was able to get file uploads working with the following code.
rest("/images").description("Image Upload Service")
.consumes("multipart/form-data").produces("application/json")
.post().description("Uploads image")
.to("direct:uploadImage");
from("direct:uploadImage")
.process(new Processor() {
#Override
public void process(Exchange exchange) throws Exception {
MediaType mediaType =
exchange.getIn().getHeader(Exchange.CONTENT_TYPE, MediaType.class);
InputRepresentation representation =
new InputRepresentation(
exchange.getIn().getBody(InputStream.class), mediaType);
try {
List<FileItem> items =
new RestletFileUpload(
new DiskFileItemFactory()).parseRepresentation(representation);
for (FileItem item : items) {
if (!item.isFormField()) {
InputStream inputStream = item.getInputStream();
Path destination = Paths.get("MyFile.jpg");
Files.copy(inputStream, destination,
StandardCopyOption.REPLACE_EXISTING);
}
}
} catch (FileUploadException | IOException e) {
e.printStackTrace();
}
}
});
you can do this with restdsl even if you are not using restlet (exemple jetty) for your restdsl component.
you need to turn restdinding of first for that route and reate two classes to handle the multipart that is in your body.
you need two classes :
DWRequestContext
DWFileUpload
and then you use them in your custom processor
here is the code :
DWRequestContext.java
import org.apache.camel.Exchange;
import org.apache.commons.fileupload.RequestContext;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
public class DWRequestContext implements RequestContext {
private Exchange exchange;
public DWRequestContext(Exchange exchange) {
this.exchange = exchange;
}
public String getCharacterEncoding() {
return StandardCharsets.UTF_8.toString();
}
//could compute here (we have stream cache enabled)
public int getContentLength() {
return (int) -1;
}
public String getContentType() {
return exchange.getIn().getHeader("Content-Type").toString();
}
public InputStream getInputStream() throws IOException {
return this.exchange.getIn().getBody(InputStream.class);
}
}
DWFileUpload.java
import org.apache.camel.Exchange;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUpload;
import org.apache.commons.fileupload.FileUploadException;
import java.util.List;
public class DWFileUpload extends
FileUpload {
public DWFileUpload() {
super();
}
public DWFileUpload(FileItemFactory fileItemFactory) {
super(fileItemFactory);
}
public List<FileItem> parseInputStream(Exchange exchange)
throws FileUploadException {
return parseRequest(new DWRequestContext(exchange));
}
}
you can define your processor like this:
routeDefinition.process(new Processor() {
#Override
public void process(Exchange exchange) throws Exception {
// Create a factory for disk-based file items
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
DWFileUpload upload = new DWFileUpload(factory);
java.util.List<FileItem> items = upload.parseInputStream(exchange);
//here I assume I have only one, but I could split it here somehow and link them to camel properties...
//with this, the first file sended with your multipart replaces the body
// of the exchange for the next processor to handle it
exchange.getIn().setBody(items.get(0).getInputStream());
}
});
I stumbled into the same requirement of having to consume a multipart request (containing file data including binary) through Apache Camel Restlet component.
Even though 2.17.x is out, since my project was part of a wider framework / application, I had to be using version 2.12.4.
Initially, my solution drew a lot from restlet-jdbc example yielded data in exchange that although was successfully retrieving text files but I was unable to retrieve correct binary content.
I attempted to dump the data directly into a file to inspect the content using following code (abridged).
from("restlet:/upload?restletMethod=POST")
.to("direct:save-files");
from("direct:save-files")
.process(new org.apache.camel.Processor(){
public void process(org.apache.camel.Exchange exchange){
/*
* Code to sniff exchange content
*/
}
})
.to("file:///C:/<path to a folder>");
;
I used org.apache.commons.fileupload.MultipartStream from apache fileuplaod library to write following utility class to parse Multipart request from a file. It worked successfully when the output of a mulitpart request from Postman was fed to it. However, failed to parse content of the file created by Camel (even through to eyes content of both files looked similar).
public class MultipartParserFileCreator{
public static final String DELIMITER = "\\r?\\n";
public static void main(String[] args) throws Exception {
// taking it from the content-type in exchange
byte[] boundary = "------5lXVNrZvONBWFXxd".getBytes();
FileInputStream fis = new FileInputStream(new File("<path-to-file>"));
extractFile(fis, boundary);
}
public static void extractFile(InputStream is, byte[] boundary) throws Exception {
MultipartStream multipartStream = new MultipartStream(is, boundary, 1024*4, null);
boolean nextPart = multipartStream.skipPreamble();
while (nextPart) {
String headers = multipartStream.readHeaders();
if(isFileContent(headers)) {
String filename = getFileName(headers);
File file = new File("<dir-where-file-created>"+filename);
if(!file.exists()) {
file.createNewFile();
}
FileOutputStream fos = new FileOutputStream(file);
multipartStream.readBodyData(fos);
fos.flush();
fos.close();
}else {
multipartStream.readBodyData(System.out);
}
nextPart = multipartStream.readBoundary();
}
}
public static String[] getContentDispositionTokens(String headersJoined) {
String[] headers = headersJoined.split(DELIMITER, -1);
for(String header: headers) {
System.out.println("Processing header: "+header);
if(header != null && header.startsWith("Content-Disposition:")) {
return header.split(";");
}
}
throw new RuntimeException(
String.format("[%s] header not found in supplied headers [%s]", "Content-Disposition:", headersJoined));
}
public static boolean isFileContent(String header) {
String[] tokens = getContentDispositionTokens(header);
for (String token : tokens) {
if (token.trim().startsWith("filename")) {
return true;
}
}
return false;
}
public static String getFileName(String header) {
String[] tokens = getContentDispositionTokens(header);
for (String token : tokens) {
if (token.trim().startsWith("filename")) {
String filename = token.substring(token.indexOf("=") + 2, token.length()-1);
System.out.println("fileName is " + filename);
return filename;
}
}
return null;
}
}
On debugging through the Camel code, I noticed that at one stage Camel is converting the entire content into String. After a point I had to stop pursuing this approach as there was very little on net applicable for version 2.12.4 and my work was not going anywhere.
Finally, I resorted to following solution
Write an implementation of HttpServletRequestWrapper to allow
multiple read of input stream. One can get an idea from
How to read request.getInputStream() multiple times
Create a filter that uses the above to wrap HttpServletRequest object, reads and extract the file to a directory Convenient way to parse incoming multipart/form-data parameters in a Servlet and attach the path to the request using request.setAttribute() method. With web.xml, configure this filter on restlet servlet
In the process method of camel route, type cast the
exchange.getIn().getBody() in HttpServletRequest object, extract the
attribute (path) use it to read the file as ByteStreamArray for
further processing
Not the cleanest, but I could achieve the objective.
Hi i am trying to implement OAuth1.0 following this tutorial in this tutorial there is a heading OAuthGetRequestToken
in which for getting request token we have to send a post request to URL
www.google.com/accounts/OAuthGetRequestToken
i am sending a post request in my code in google app engine my code is:
public class HelloWorldServlet extends HttpServlet {
#SuppressWarnings({ "unchecked", "unchecked" })
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
resp.setContentType("text/html");
resp.getWriter().println("<html><head> <meta name=\"google-site-verification\" content=\"OBFeK6hFEbTkNdcYc-SQNH9tCTpcht-HkUdj6IgCaLg\" </head>");
resp.getWriter().println("<body>Hello, world");
//String post="key=AIzaSyBgmwbZaW3-1uaVOQ9UqlyHAUxvQtHe7X0&oauth_consumer_key=iriteshmehandiratta.appspot.com";
//String param= "&oauth_callback=\"https://www.iriteshmehandiratta.appspot.com\"&scope=\"http://www.google.com/calendar/feeds\"";
//URL url=new URL("https://www.googleapis.com/prediction/v1.5/trainedmodels/10/predict?");
TreeMap<String,String> tree=new TreeMap<String,String>();
tree.put("oauth_version","1.0");
tree.put("oauth_nonce", System.currentTimeMillis()+"");
tree.put("oauth_timestamp",System.currentTimeMillis()/1000+"");
tree.put("oauth_consumer_key", "imehandirattaritesh.appspot.com");
tree.put("oauth_signature_method", "RSA-SHA1");
ServletContext context = getServletContext();
PrivateKey privKey = getPrivateKey(context,"/myrsakey11.pk8");
tree.put("oauth_callback", "https://imehandirattaritesh.appspot.com/authsub");
tree.put("scope", "https://www.google.com/calendar/feeds");
Set set = tree.entrySet();
Iterator<Map.Entry<String, String>> i = set.iterator();
String datastring="";
Map.Entry me=(Map.Entry)i.next();
datastring=me.getKey()+"=";
datastring+=me.getValue();
while(i.hasNext()) {
me = (Map.Entry)i.next();
datastring+="&"+me.getKey()+"=";
datastring+=(me.getValue());
}
String data_string="GET&https://www.google.com/accounts/OAuthGetRequestToken&"+datastring;
byte[] xx11;
String str = null;
try {
xx11 = sign(privKey,data_string);
str=new String(xx11);
resp.getWriter().println(str);
} catch (GeneralSecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
URL url=new URL("https://www.google.com/accounts/OAuthGetRequestToken?"+str);
// resp.getWriter().println(""+datastring);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
urlConnection.setRequestProperty("Authorization", " OAuth");
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
resp.getWriter().println( urlConnection.getResponseCode());
String xx="";
String xx1="";
while((xx1=in.readLine()) != null)
{
xx+=xx1;
}
resp.getWriter().println("response");
resp.getWriter().println(xx);
resp.getWriter().println("</body></html>");
}
public static PrivateKey getPrivateKey(ServletContext context,String privKeyFileName) throws IOException {
InputStream resourceContent = context.getResourceAsStream("/WEB-INF/myrsakey11.pk8");
// FileInputStream fis = new FileInputStream(privKeyFile);
DataInputStream dis = new DataInputStream(resourceContent);
#SuppressWarnings("deprecation")
String str="";
String str1="";
while((str=dis.readLine())!=null)
{
str1+=str;
}
String BEGIN = "-----BEGIN PRIVATE KEY-----";
String END = "-----END PRIVATE KEY-----";
// String str = new String(privKeyBytes);
if (str1.contains(BEGIN) && str1.contains(END)) {
str1 = str1.substring(BEGIN.length(), str1.lastIndexOf(END));
}
KeyFactory fac;
try {
fac = KeyFactory.getInstance("RSA");
EncodedKeySpec privKeySpec= new PKCS8EncodedKeySpec(Base64.decode(str1));
return fac.generatePrivate(privKeySpec);
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Base64DecoderException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidKeySpecException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
byte[] sign(PrivateKey key, String data) throws GeneralSecurityException {
Signature signature = Signature.getInstance("SHA1withRSA");
signature.initSign(key);
signature.update(data.getBytes());
return signature.sign();
}
}
first i generate data_string then sign it using my private key i get an encrypted string like this
F????T???&??$????????l:v????x???}??U-'?"?????U?[?kr^?G?(? ???qT0??]??j???5??`??$??AD??T??#<t?,#:`V????????????
then i concatenate it with
url : https://www.google.com/accounts/OAuthGetRequestToken?
and i get 400 error obviously it is not a valid uri format so i get this error.i post a query on stackoverflow a person suggest me to use sign method and after signing data_string i will get oauth_signature embedded in the return string which is variable str but in place of oauth_signature included i am getting an encrypted string can any one please tell me how to sign this data_string and what mistake i am doing ??
I would suggest you use an existing Java library for doing the OAuth. It will be much easier in the long term and you won't have to worry about debugging the protocol.