Box.net api Upload files from Salesforce - salesforce

I am using the following code to upload the files to Box.net from Salesforce using V2 api and got the following error
System.HttpResponse[Status=Not Found, StatusCode=404]
String sUrl = 'https://upload.box.com/api/2.0/files/data' ;
Http h = new Http();
HttpRequest req = new HttpRequest();
req.setEndpoint(sUrl);
req.setHeader('Authorization', newAuthorization);
req.setMethod('POST');
req.setHeader('Content-Type', 'application/pdf');
String content = '{"filename":"/Users/rmasineni/temp/DealPackage/Cederquist Credit Memo.pdf", "folder_id":"0"}';
//String content = '{"filename":"&", "folder_id":"0"}';
req.setbody(content);
HttpResponse res;
res = h.send(req);
It will be great if someone helps me on how to use Box-api V2 to upload the files .
Thanks,
Rag

Related

Validate SAML Response

I have a SAML response and few other data. Based on this, I need to validate if the response has been tampered or not. How can I do that?
What all I have?
SAML Response with Signed Message & Assertion
IdP EntityId
SP EntityId
SP ACS Endpoint
Target URL
Certificate of the IdP in X509 format.
Language needed: JAVA
Got a solution. If anyone is loking for it.
try {
InputStream is = new FileInputStream("<CERTIFICATE FILE>");
CertificateFactory cf = CertificateFactory.getInstance("X.509");
Certificate cert = cf.generateCertificate(is);
X509Certificate x509Certificate = (X509Certificate) cert;
PublicKey pk = x509Certificate.getPublicKey();
BasicX509Credential publicCredential = new BasicX509Credential();
publicCredential.setPublicKey(pk);
SignatureValidator signatureValidator = new SignatureValidator(publicCredential);
SignableSAMLObject signableSAMLObject = (SignableSAMLObject) <XML OBJECT>;
Signature signature = signableSAMLObject.getSignature();
signatureValidator.validate(signature);
}catch(Exception ex){
// fail this.
}
XML Object can be obtained from SAML Message using marshaller in following way:
String encodedMessage = request.getParameter(PARAM_SAML);
String decodedMessage = new String(Base64.decodeBase64(encodedMessage.getBytes()));
DefaultBootstrap.bootstrap();
BasicParserPool ppMgr = new BasicParserPool();
ppMgr.setNamespaceAware(true);
Document responseRoot = ppMgr.parse(new StringReader(decodedMessage));
UnmarshallerFactory unmarshallFactory = Configuration.getUnmarshallerFactory();
Unmarshaller unmarshaller = unmarshallFactory.getUnmarshaller(responseRoot.getDocumentElement());
XMLObject obj = unmarshaller.unmarshall(responseRoot.getDocumentElement());

Using ComponentSpace SAML to sign and post request

I am using component space libraries to create SAML request and sign it then post it to URL, However request is not posting successfully because i need to use RSA algorithm key but so far i found that it is not available in SamlKeyAlgorithm also i need to change the Key size to 2048 below are my method that i used to send the request.
private void SendTawtheeqRequest()
{
string ConsumerServiceUrl = "https://tawtheeq.sa:8443/identity-gateway-test/ReceiveSAMLRequest";
// Create a SAML response object.
Response samlResponse = new Response();
// Assign the consumer service url.
samlResponse.Destination = ConsumerServiceUrl;
Issuer issuer = new Issuer(GetAbsoluteUrl("~/"));
samlResponse.Issuer = issuer;
samlResponse.Status = new Status(SamlPrimaryStatusCode.Success, null);
Assertion samlAssertion = new Assertion();
samlAssertion.Issuer = issuer;
// Use the local user's local identity.
Subject subject = new Subject(new NameId(User.Identity.Name));
SubjectConfirmation subjectConfirmation = new SubjectConfirmation(SamlSubjectConfirmationMethod.Bearer);
SubjectConfirmationData subjectConfirmationData = new SubjectConfirmationData();
subjectConfirmationData.Recipient = ConsumerServiceUrl;
subjectConfirmation.SubjectConfirmationData = subjectConfirmationData;
subject.SubjectConfirmations.Add(subjectConfirmation);
samlAssertion.Subject = subject;
// Create a new authentication statement.
AuthnStatement authnStatement = new AuthnStatement();
authnStatement.AuthnContext = new AuthnContext();
authnStatement.AuthnContext.AuthnContextClassRef = new AuthnContextClassRef(SamlAuthenticationContext.Password);
samlAssertion.Statements.Add(authnStatement);
X509Certificate2 encryptingCert = new X509Certificate2(Path.Combine(HttpRuntime.AppDomainAppPath, "my-bank1-public.cer"));
EncryptedAssertion encryptedSamlAssertion = new EncryptedAssertion(samlAssertion, encryptingCert, new EncryptionMethod(SamlKeyAlgorithm.TripleDesCbc));
samlResponse.Assertions.Add(encryptedSamlAssertion);
samlResponse.Assertions.Add(samlAssertion);
samlResponse.SendHttpPost(Response.OutputStream, ConsumerServiceUrl, "10");
}

JavaMail on Google App Engine sending HTML email with attachments - ignores first attachment

I am using Java on Google App Engine and trying to send an email with multiple attachments.
What I am finding is that it is for some reason missing off the first attachment.
Basically if filesToAttach contains 1 file, then there will be no attachments.
If filesToAttach contains 4 files - A, B, C and D, then the message that comes through will have B, C and D attached. Really bizarre.
The code I am using is as below. Any suggestions as to how to rectify this greatly appreciated.
The output that the log.info calls generate appears to show the correct number of files have been attached.
Properties props = new Properties();
Session session = Session.getInstance(props);
Message message = new MimeMessage(session);
String fromEmail = "admin#" + ApiProxy.getCurrentEnvironment().getAppId() + ".appspotmail.com";
message.setFrom(new InternetAddress(fromEmail, "MyApp Admin"));
message.addRecipients(Message.RecipientType.BCC, addresses);
message.setSubject(subject);
MimeMultipart multipart = new MimeMultipart();
MimeBodyPart htmlPart = new MimeBodyPart();
htmlPart.setContent(htmlBody, "text/html");
multipart.addBodyPart(htmlPart);
for(FileToAttach fileToAttach : filesToAttach) {
MimeBodyPart fileMimeBodyPart = new MimeBodyPart();
DataSource dataSource = new ByteArrayDataSource(fileToAttach.getContents(), "application/octet-stream");
fileMimeBodyPart.setDataHandler(new DataHandler(dataSource));
fileMimeBodyPart.setFileName(fileToAttach.getFileName());
log.info("attaching file " + fileToAttach.getFileName() + " of " + fileToAttach.getContents().length + " bytes");
multipart.addBodyPart(fileMimeBodyPart);
}
message.setContent(multipart);
log.info("the multipart contains " + multipart.getCount() + " parts and isComplete = " + multipart.isComplete());
Transport.send(message);
log.info("called Transport.send");

Solr Change CommonsHttpSolrServer To HttpSolrServer

For Basic Authentication in solr 3.5 I am using the following code,
String url = "http://192.168.192.11:8080/solr/FormResponses";
CommonsHttpSolrServer server = new CommonsHttpSolrServer( url );
String username = "user";
String password = "user123";
Credentials defaultcreds = new UsernamePasswordCredentials(username, password);
server.getHttpClient().getState().setCredentials(AuthScope.ANY, defaultcreds);
server.getHttpClient().getParams().setAuthenticationPreemptive(true);
In solr 4.0 CommonsHttpSolrServer is not available, so I want to replace it with
HttpSolrServer. Can anyone help me to fix this?
Change the code as follows :
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.solr.client.solrj.impl.HttpSolrServer;
String url = "http://192.168.192.11:8080/solr/FormResponses";
HttpSolrServer server = new HttpSolrServer( url );
DefaultHttpClient client = (DefaultHttpClient) server.getHttpClient();
UsernamePasswordCredentials defaultcreds = new UsernamePasswordCredentials("user", "user123");
client.getCredentialsProvider().setCredentials(AuthScope.ANY, defaultcreds);
For server.getHttpClient().getParams().setAuthenticationPreemptive(true) in HttpClient 4 you can use the solution described here.
Finally I find the answer my self,
String url = "http://192.168.192.11:8080/solr/FormResponses";
DefaultHttpClient httpclient = new DefaultHttpClient();
httpclient.getCredentialsProvider().setCredentials(
AuthScope.ANY, new UsernamePasswordCredentials("user", "user123"));
SolrServer solrServer = new HttpSolrServer(url, httpclient);
You need to add the JAR solr-solrj-4.0.0.jar for HttpClientUtil .
Then use below code :
HttpSolrServer solrServer = new HttpSolrServer("http://localhost:8080/solr/"+url);
HttpClientUtil.setBasicAuth((DefaultHttpClient) solrServer.getHttpClient(),
"USERNAME", "PASSWORD");
That worked for me.
This is the only way that works for me:
String url = "192.168.192.11:8080/solr/FormResponses";
String username = "user";
String password = "user123";
HttpSolrServer server = new HttpSolrServer("http://" + username + ":" + password + "#" + url);

WPF - Web Request being truncated

I'm using the bing api to request some results.. when I run my code the response string is truncated so that its missing the first 10-50 characters.. when I paste the exact same request in the browser it returns the results just fine..
Here is my code.. what am I doing wrong?
string AppId = "My APP ID HERE :O ";
string url = "http://api.search.live.net/xml.aspx?Appid={0}&sources={1}&query={2}";
string completeUri = String.Format(url, AppId, "web", validateforweb(Artist) + "%20" + validateforweb(Song) + "%20" + "Lyrics");
HttpWebRequest webRequest = null;
webRequest = (HttpWebRequest)WebRequest.Create(completeUri);
HttpWebResponse webResponse = null;
webResponse = (HttpWebResponse)webRequest.GetResponse();
XmlReader xmlReader = null;
Stream s = webResponse.GetResponseStream();
xmlReader = XmlReader.Create(s);
StreamReader reader;
reader = new StreamReader(s);
string str = reader.ReadToEnd();
I suspect it's related to the fact you're creating 2 readers on the stream (XmlReader and StreamReader). The XmlReader starts buffering data from the stream as soon as you create it, so when the StreamReader starts reading from the same stream, it misses the part of the data that has been buffered by the XmlReader.
You can't use 2 readers on the same stream, they will conflict with each other.

Resources